UNPKG

@tiampersian/kendo-jalali-date-inputs

Version:

angular jalali ( persian ) date time picker base on kendo-angular-dateinputs

2,073 lines 86.2 kB
import * as i0 from '@angular/core';
import { LOCALE_ID, Inject, Injectable, TemplateRef, ViewChild, Component, createComponent, EnvironmentInjector, Optional, SkipSelf, Self, Directive, NgModule } from '@angular/core';
import '@angular/localize/init';
import * as i1 from '@progress/kendo-angular-intl';
import { CldrIntlService, IntlService, setData, localeData as localeData$1 } from '@progress/kendo-angular-intl';
import dayjs from 'dayjs';
import isBetween from 'dayjs/plugin/isBetween';
import localeData from 'dayjs/plugin/localeData';
import updateLocale from 'dayjs/plugin/updateLocale';
import jalaliday from 'jalaliday';
import { CenturyViewService, DecadeViewService, MonthViewService, WeekNamesService, YearViewService, NavigationComponent, DateInputComponent } from '@progress/kendo-angular-dateinputs';
import { debounceTime } from 'rxjs/operators';
import '@angular/localize';
import { IconWrapperComponent } from '@progress/kendo-angular-icons';
import { arrowsSwapIcon } from '@progress/kendo-svg-icons';
import { Subject } from 'rxjs';
import { getDate, addDecades, addYears, dayOfWeek, addDays, addMonths as addMonths$1, isEqual } from '@progress/kendo-date-math';
import { Constants } from '@progress/kendo-dateinputs-common/dist/es2015/common/constants';
import { DateObject } from '@progress/kendo-dateinputs-common/dist/es2015/common/dateobject';
import { Key } from '@progress/kendo-dateinputs-common/dist/es2015/common/key';
import { KeyCode } from '@progress/kendo-dateinputs-common/dist/es2015/common/keycode';
import { Mask } from '@progress/kendo-dateinputs-common/dist/es2015/common/mask';
import { parseToInt } from '@progress/kendo-dateinputs-common/dist/es2015/common/utils';
import { DateInput } from '@progress/kendo-dateinputs-common/dist/es2015/dateinput/dateinput';
import { DateInputInteractionMode } from '@progress/kendo-dateinputs-common/dist/es2015/dateinput/interaction-mode';
import { approximateStringMatching, padZero } from '@progress/kendo-dateinputs-common/dist/es2015/dateinput/utils';

var DatePickerType;
(function (DatePickerType) {
    DatePickerType["jalali"] = "jalali";
    DatePickerType["gregory"] = "gregory";
})(DatePickerType || (DatePickerType = {}));

class DateTimeNumberService {
    configs;
    usePersianNumber;
    constructor(localeId, configs) {
        this.configs = configs;
        this.setLocaleId(localeId);
        this.init();
    }
    setLocaleId(value) {
        this.usePersianNumber = value === 'fa' || value === 'fa-IR';
    }
    init() {
        if (this.configs?.usePersianNumber === false) {
            return;
        }
        const me = this;
        // dayjs.localeData().months();
        const te = dayjs.prototype.format;
        dayjs.prototype.format = function (format) {
            if (!me.usePersianNumber) {
                return te.call(this, format);
            }
            let result = te.call(this, format);
            result = result.toPerNumber().replace(/,/g, '،');
            return result;
        };
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: DateTimeNumberService, deps: [{ token: LOCALE_ID }, { token: 'CONFIGS' }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: DateTimeNumberService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: DateTimeNumberService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: undefined, decorators: [{
                    type: Inject,
                    args: [LOCALE_ID]
                }] }, { type: undefined, decorators: [{
                    type: Inject,
                    args: ['CONFIGS']
                }] }] });

class JalaliCldrIntlService extends CldrIntlService {
    originalLocaleId;
    dateTimeNumberService;
    isJalali;
    isGregorian;
    datePickerType;
    localeIdByDatePickerType = '';
    get isLocaleIran() {
        return this.localeId === 'fa-IR' || this.localeId === 'fa';
    }
    get calendarType() {
        return this.localeIdByDatePickerType === 'fa' ? 'jalali' : 'gregory';
    }
    defaultTitleTemplate;
    $calendarType = new Subject();
    isFirst = true;
    jalaliMonths;
    gregorianMonths;
    constructor(originalLocaleId, dateTimeNumberService) {
        super(originalLocaleId);
        this.originalLocaleId = originalLocaleId;
        this.dateTimeNumberService = dateTimeNumberService;
        this.changeType();
        this.prepareMonthData();
    }
    prepareMonthData() {
        this.jalaliMonths = Array.from(Array(12).keys()).map((x, i) => {
            return this.getDayJsValue('' + (i + 1)).format('MMMM');
        });
        this.jalaliMonths.splice(this.jalaliMonths.length, 0, ...this.jalaliMonths.splice(0, 3));
        this.gregorianMonths = this.getDayJsValue().localeData().monthsShort();
    }
    firstDay(localeId) {
        return super.firstDay(this.localeIdByDatePickerType);
    }
    setTitleTemplate(template) {
        this.defaultTitleTemplate = template;
    }
    changeType(value) {
        this.datePickerType = this.getType(value);
        if (this.datePickerType === DatePickerType.jalali) {
            this.isJalali = true;
            this.isGregorian = false;
            this.localeIdByDatePickerType = 'fa';
            this.reload();
            return;
        }
        this.isJalali = false;
        this.isGregorian = true;
        this.localeIdByDatePickerType = 'en';
        this.reload();
    }
    reload() {
        const tem = super.localeId;
        this.changeLocaleId('en');
        this.changeLocaleId(tem);
        this.$calendarType.next(this.localeIdByDatePickerType);
        this.changes.next(super.localeId);
    }
    changeLocaleId(value) {
        super.localeId = value;
        this.dateTimeNumberService.setLocaleId(value);
        this.prepareMonthData();
        this.notify();
    }
    toggleType() {
        this.changeType(this.datePickerType === DatePickerType.jalali ? DatePickerType.gregory : DatePickerType.jalali);
        if (this.isFirst) {
            this.isFirst = false;
            // to fix old version of chrome
            // setTimeout(() => {
            //   this.toggleType();
            //   setTimeout(() => {
            //     this.toggleType();
            //   }, 0);
            // }, 0);
        }
    }
    getType(value) {
        if (value) {
            return value;
        }
        if (this.originalLocaleId === 'fa-IR' || this.originalLocaleId === 'fa') {
            return DatePickerType.jalali;
        }
        return DatePickerType.gregory;
    }
    formatNumber(value, format, localeId) {
        localeId = localeId || this.localeId;
        if (localeId === 'fa' || localeId === 'ar') {
            return super.formatNumber(value, format, localeId).toPerNumber();
        }
        return super.formatNumber(value, format, localeId);
    }
    getDayJsValue(value, localeId) {
        return dayjs(value).calendar(this.calendarType).locale(localeId || this.localeId);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliCldrIntlService, deps: [{ token: LOCALE_ID }, { token: DateTimeNumberService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliCldrIntlService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliCldrIntlService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: undefined, decorators: [{
                    type: Inject,
                    args: [LOCALE_ID]
                }] }, { type: DateTimeNumberService }] });

class KendoJalaliHeaderTitleTemplateComponent {
    localeService;
    templateRef = TemplateRef;
    calendarType;
    calendarTypes = {
        [DatePickerType.gregory]: $localize `:@@jalali:Jalali`,
        [DatePickerType.jalali]: $localize `:@@gregorian:Gregorian`,
    };
    calendarTypesSymbol = {
        [DatePickerType.gregory]: '☼',
        [DatePickerType.jalali]: '†',
    };
    xIcon = arrowsSwapIcon;
    constructor(localeService) {
        this.localeService = localeService;
        this.calendarType = this.localeService.datePickerType;
    }
    ngAfterViewInit() {
        this.localeService.setTitleTemplate(this);
    }
    toggleCalendarType(event) {
        this.localeService.toggleType();
        this.calendarType = this.localeService.datePickerType;
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoJalaliHeaderTitleTemplateComponent, deps: [{ token: IntlService }], target: i0.ɵɵFactoryTarget.Component });
    static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "19.0.6", type: KendoJalaliHeaderTitleTemplateComponent, isStandalone: true, selector: "ng-component", viewQueries: [{ propertyName: "templateRef", first: true, predicate: ["template"], descendants: true, read: TemplateRef }], ngImport: i0, template: `
  <ng-template #template kendoCalendarHeaderTitleTemplate let-title>
    <span >{{title}}</span>
    <button i18n-title="@@changeCalendarType" title="Change Calendar Type" class="header-calendar-type k-button k-rounded-lg k-button-sm k-button-link-base k-button-link" (click)="toggleCalendarType($event)">
      {{calendarTypes[calendarType]}}
      <strong class="k-color-primary">{{calendarTypesSymbol[calendarType]}}</strong>
      <kendo-icon-wrapper name="arrows-swap" [svgIcon]="xIcon" />
    </button>
  </ng-template>`, isInline: true, styles: ["::ng-deep .k-calendar{direction:ltr}::ng-deep .k-calendar kendo-virtualization.k-flex.k-content.k-scrollable{--kendo-scrollbar-width: -15px}::ng-deep .k-calendar kendo-calendar-navigation kendo-virtualization.k-flex.k-content.k-scrollable{--kendo-scrollbar-width: 0px}::ng-deep .k-calendar kendo-calendar-navigation kendo-virtualization.k-flex.k-content.k-scrollable>ul{display:flex;flex-direction:column;align-items:center}::ng-deep .k-calendar-title{display:flex;text-align:left;width:100%;outline:unset!important;cursor:unset!important;opacity:unset!important;filter:unset!important;pointer-events:unset!important;box-shadow:unset!important}::ng-deep .k-calendar-title:hover:before,::ng-deep .k-calendar-title:active:before{background:none}::ng-deep .k-calendar-title .header-calendar-type{text-align:center;text-transform:capitalize;padding:0;margin-inline-start:10px;border:1px solid var(--kendo-color-base-subtle);vertical-align:baseline}::ng-deep .k-calendar-title .header-calendar-type .k-icon{font-size:14px;font-weight:700}::ng-deep .k-calendar-title .header-title{text-align:left;padding:0;cursor:pointer}::ng-deep .k-calendar-title.k-state-disabled .header-title{outline:none;cursor:default;opacity:.6;filter:grayscale(.1);pointer-events:none;box-shadow:none}::ng-deep .rtl kendo-dateinput input,::ng-deep [dir=rtl] kendo-dateinput input{direction:rtl!important;text-align:right!important;unicode-bidi:embed!important}::ng-deep .rtl kendo-calendar-navigation.k-calendar-navigation kendo-virtualization,::ng-deep [dir=rtl] kendo-calendar-navigation.k-calendar-navigation kendo-virtualization{right:unset!important}::ng-deep .rtl kendo-calendar-navigation.k-calendar-navigation kendo-virtualization ul>li,::ng-deep [dir=rtl] kendo-calendar-navigation.k-calendar-navigation kendo-virtualization ul>li{text-align:center}\n"], dependencies: [{ kind: "component", type: IconWrapperComponent, selector: "kendo-icon-wrapper", inputs: ["name", "svgIcon", "innerCssClass", "customFontClass", "size"], exportAs: ["kendoIconWrapper"] }] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoJalaliHeaderTitleTemplateComponent, decorators: [{
            type: Component,
            args: [{ template: `
  <ng-template #template kendoCalendarHeaderTitleTemplate let-title>
    <span >{{title}}</span>
    <button i18n-title="@@changeCalendarType" title="Change Calendar Type" class="header-calendar-type k-button k-rounded-lg k-button-sm k-button-link-base k-button-link" (click)="toggleCalendarType($event)">
      {{calendarTypes[calendarType]}}
      <strong class="k-color-primary">{{calendarTypesSymbol[calendarType]}}</strong>
      <kendo-icon-wrapper name="arrows-swap" [svgIcon]="xIcon" />
    </button>
  </ng-template>`, imports: [
                        IconWrapperComponent
                    ], styles: ["::ng-deep .k-calendar{direction:ltr}::ng-deep .k-calendar kendo-virtualization.k-flex.k-content.k-scrollable{--kendo-scrollbar-width: -15px}::ng-deep .k-calendar kendo-calendar-navigation kendo-virtualization.k-flex.k-content.k-scrollable{--kendo-scrollbar-width: 0px}::ng-deep .k-calendar kendo-calendar-navigation kendo-virtualization.k-flex.k-content.k-scrollable>ul{display:flex;flex-direction:column;align-items:center}::ng-deep .k-calendar-title{display:flex;text-align:left;width:100%;outline:unset!important;cursor:unset!important;opacity:unset!important;filter:unset!important;pointer-events:unset!important;box-shadow:unset!important}::ng-deep .k-calendar-title:hover:before,::ng-deep .k-calendar-title:active:before{background:none}::ng-deep .k-calendar-title .header-calendar-type{text-align:center;text-transform:capitalize;padding:0;margin-inline-start:10px;border:1px solid var(--kendo-color-base-subtle);vertical-align:baseline}::ng-deep .k-calendar-title .header-calendar-type .k-icon{font-size:14px;font-weight:700}::ng-deep .k-calendar-title .header-title{text-align:left;padding:0;cursor:pointer}::ng-deep .k-calendar-title.k-state-disabled .header-title{outline:none;cursor:default;opacity:.6;filter:grayscale(.1);pointer-events:none;box-shadow:none}::ng-deep .rtl kendo-dateinput input,::ng-deep [dir=rtl] kendo-dateinput input{direction:rtl!important;text-align:right!important;unicode-bidi:embed!important}::ng-deep .rtl kendo-calendar-navigation.k-calendar-navigation kendo-virtualization,::ng-deep [dir=rtl] kendo-calendar-navigation.k-calendar-navigation kendo-virtualization{right:unset!important}::ng-deep .rtl kendo-calendar-navigation.k-calendar-navigation kendo-virtualization ul>li,::ng-deep [dir=rtl] kendo-calendar-navigation.k-calendar-navigation kendo-virtualization ul>li{text-align:center}\n"] }]
        }], ctorParameters: () => [{ type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }] }], propDecorators: { templateRef: [{
                type: ViewChild,
                args: ['template', { read: TemplateRef }]
            }] } });

function HeaderTitleTemplateFactory(environmentInjector) {
    const temp = createComponent(KendoJalaliHeaderTitleTemplateComponent, { environmentInjector });
    temp.changeDetectorRef.detectChanges();
    return temp.instance;
}

const range = (start, end, step = 1) => {
    const result = [];
    for (let i = start; i < end; i = i + step) {
        result.push(i);
    }
    return result;
};
const EMPTY_SELECTIONRANGE = { start: null, end: null };
const getToday = () => getDate(new Date());
const isInSelectionRange = (value, selectionRange) => {
    const { start, end } = selectionRange || EMPTY_SELECTIONRANGE;
    if (!start || !end) {
        return false;
    }
    return start < value && value < end;
};
const isInRange = (dt, min, max) => {
    return dayjs(dt).isBetween(min, max);
};
const firstYearOfDecade = (dt, localeId) => {
    return getDayJsValue(dt, localeId).add(-(getYear(dt, localeId) % 10), 'year').toDate();
};
const lastYearOfDecade = (dt, localeId) => {
    return getDayJsValue(dt, localeId).add((9 - (getYear(dt, localeId) % 10)), 'year').toDate();
};
const firstDayOfMonth = (dt, localeId) => {
    return getDayJsValue(dt, localeId).startOf('month').toDate();
};
const lastDayOfMonth = (dt, localeId) => {
    return getDayJsValue(dt, localeId).endOf('month').toDate();
};
const addMonths = (dt, value, localeId) => {
    return getDayJsValue(dt, localeId).add(value, 'month').toDate();
};
const getCalendarType = (localeId) => {
    return (localeId === 'fa' || localeId === 'fa-IR') ? 'jalali' : 'gregory';
};
const getDayJsValue = (dt, localeId) => {
    return dayjs(dt).calendar(getCalendarType(localeId));
};
const firstDecadeOfCentury = (dt, localeId) => {
    return getDayJsValue(dt, localeId).add((-(getYear(dt, localeId) % 100)), 'year').toDate();
};
const lastDecadeOfCentury = (dt, localeId) => {
    return getDayJsValue(dt, localeId).add((-(getYear(dt, localeId) % 100)) + 90, 'year').toDate();
};
const shiftWeekNames = (names, offset) => (names.slice(offset).concat(names.slice(0, offset)));
var Action;
(function (Action) {
    Action[Action["Left"] = 0] = "Left";
    Action[Action["Right"] = 1] = "Right";
    Action[Action["Up"] = 2] = "Up";
    Action[Action["Down"] = 3] = "Down";
    Action[Action["PrevView"] = 4] = "PrevView";
    Action[Action["NextView"] = 5] = "NextView";
    Action[Action["FirstInView"] = 6] = "FirstInView";
    Action[Action["LastInView"] = 7] = "LastInView";
    Action[Action["LowerView"] = 8] = "LowerView";
    Action[Action["UpperView"] = 9] = "UpperView";
})(Action || (Action = {}));
const isPresent = (value) => value !== undefined && value !== null;
function getYear(dt, localeId) {
    return getDayJsValue(dt, localeId).year();
}

const EMPTY_DATA$2 = [[]];
const CELLS_LENGTH$2 = 4;
const ROWS_LENGTH$2 = 3;

class JalaliCenturyViewService extends CenturyViewService {
    _intlService;
    constructor(_intlService) {
        super();
        this._intlService = _intlService;
    }
    title(current) {
        if (!current) {
            return '';
        }
        const temp = this._intlService.getDayJsValue(lastDecadeOfCentury(current, this._intlService.localeIdByDatePickerType)).format('YYYY');
        return `${this._intlService.getDayJsValue(firstDecadeOfCentury(current, this._intlService.localeIdByDatePickerType)).format('YYYY')} - ${temp}`;
    }
    navigationTitle(value) {
        return `${this._intlService.getDayJsValue(firstDecadeOfCentury(value, this._intlService.localeIdByDatePickerType)).format('YYYY')}`;
    }
    data(options) {
        const { cellUID, focusedDate, isActiveView, max, min, selectedDate, selectionRange = {}, viewDate } = options;
        if (!viewDate) {
            return EMPTY_DATA$2;
        }
        const cells = range(0, CELLS_LENGTH$2);
        const firstDate = firstDecadeOfCentury(viewDate, this._intlService.localeIdByDatePickerType);
        const lastDate = lastDecadeOfCentury(viewDate, this._intlService.localeIdByDatePickerType);
        const isSelectedDateInRange = isInRange(selectedDate, min, max);
        const today = getToday();
        const data = range(0, ROWS_LENGTH$2).map(rowOffset => {
            const baseDate = addDecades(firstDate, rowOffset * CELLS_LENGTH$2);
            return cells.map(cellOffset => {
                const cellDate = super['normalize'](addDecades(baseDate, cellOffset), min, max);
                if (!this.isInRange(cellDate, firstDate, lastDate)) {
                    return null;
                }
                const isRangeStart = this.isEqual(cellDate, selectionRange.start);
                const isRangeEnd = this.isEqual(cellDate, selectionRange.end);
                const isInMiddle = !isRangeStart && !isRangeEnd;
                const isRangeMid = isInMiddle && isInSelectionRange(cellDate, selectionRange);
                const title = this._intlService.getDayJsValue(cellDate).format('YYYY');
                return {
                    formattedValue: title,
                    id: `${cellUID}${cellDate.getTime()}`,
                    isFocused: this.isEqual(cellDate, focusedDate),
                    isSelected: isActiveView && isSelectedDateInRange && this.isEqual(cellDate, selectedDate),
                    isWeekend: false,
                    isRangeStart,
                    isRangeMid,
                    isRangeEnd,
                    isRangeSplitEnd: isRangeMid && this.isEqual(cellDate, lastDate),
                    isRangeSplitStart: isRangeMid && this.isEqual(cellDate, firstDate),
                    isToday: this.isEqual(cellDate, today),
                    title,
                    value: cellDate
                };
            });
        });
        return data;
    }
    isInRange(candidate, min, max) {
        const year = firstYearOfDecade(candidate, this._intlService.localeIdByDatePickerType).getFullYear();
        const aboveMin = !min || firstYearOfDecade(min, this._intlService.localeIdByDatePickerType).getFullYear() <= year;
        const belowMax = !max || year <= firstYearOfDecade(max, this._intlService.localeIdByDatePickerType).getFullYear();
        return aboveMin && belowMax;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliCenturyViewService, deps: [{ token: IntlService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliCenturyViewService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliCenturyViewService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }] }] });

class JalaliDecadeViewService extends DecadeViewService {
    _intlService;
    constructor(_intlService) {
        super();
        this._intlService = _intlService;
    }
    title(value) {
        if (!value) {
            return '';
        }
        const firstYear = this._intlService.getDayJsValue(firstYearOfDecade(value, this._intlService.localeIdByDatePickerType)).format('YYYY');
        const lastYear = this._intlService.getDayJsValue(lastYearOfDecade(value, this._intlService.localeIdByDatePickerType)).format('YYYY');
        if (this._intlService.isLocaleIran) {
            return `${lastYear} - ${firstYear}`;
        }
        return `${firstYear} - ${lastYear}`;
    }
    navigationTitle(value) {
        if (!value) {
            return '';
        }
        return `${this._intlService.getDayJsValue(firstYearOfDecade(value, this._intlService.localeIdByDatePickerType)).format('YYYY')}`;
    }
    data(options) {
        const { cellUID, focusedDate, isActiveView, max, min, selectedDates, selectionRange = EMPTY_SELECTIONRANGE, viewDate } = options;
        if (!viewDate) {
            return EMPTY_DATA$2;
        }
        const cells = range(0, CELLS_LENGTH$2);
        const firstDate = firstYearOfDecade(viewDate, this._intlService.localeIdByDatePickerType);
        const lastDate = lastYearOfDecade(viewDate, this._intlService.localeIdByDatePickerType);
        const today = getToday();
        // isInRange(selectedDate, min, max)
        const data = range(0, ROWS_LENGTH$2).map(rowOffset => {
            const baseDate = addYears(firstDate, rowOffset * CELLS_LENGTH$2);
            return cells.map(cellOffset => {
                const cellDate = super['normalize'](addYears(baseDate, cellOffset), min, max);
                const nextDecade = cellDate.getFullYear() > lastDate.getFullYear();
                if (!this.isInRange(cellDate, min, max) || nextDecade) {
                    return null;
                }
                const isRangeStart = this.isEqual(cellDate, selectionRange.start);
                const isRangeEnd = this.isEqual(cellDate, selectionRange.end);
                const isInMiddle = !isRangeStart && !isRangeEnd;
                const isRangeMid = isInMiddle && isInSelectionRange(cellDate, selectionRange);
                const title = this._intlService.getDayJsValue(cellDate).format('YYYY');
                return {
                    formattedValue: title,
                    id: `${cellUID}${cellDate.getTime()}`,
                    isFocused: this.isEqual(cellDate, focusedDate),
                    isSelected: isActiveView && selectedDates.some(date => this.isEqual(cellDate, date)),
                    isWeekend: false,
                    isRangeStart,
                    isRangeMid,
                    isRangeEnd,
                    isRangeSplitEnd: isRangeMid && this.isEqual(cellDate, lastDate),
                    isRangeSplitStart: isRangeMid && this.isEqual(cellDate, firstDate),
                    isToday: this.isEqual(cellDate, today),
                    title,
                    value: cellDate
                };
            });
        });
        return data;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliDecadeViewService, deps: [{ token: IntlService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliDecadeViewService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliDecadeViewService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }] }] });

const EMPTY_DATA$1 = [[]];
const CELLS_LENGTH$1 = 7;
const ROWS_LENGTH$1 = 6;

class JalaliMonthViewService extends MonthViewService {
    intl;
    constructor(intl) {
        super(intl);
        this.intl = intl;
    }
    value(current) {
        if (!current) {
            return '';
        }
        const res = this.intl.getDayJsValue(current).format('DD').toString();
        return res;
    }
    abbrMonthNames2() {
        if (this.intl.isJalali) {
            return this.intl.jalaliMonths;
        }
        return this.intl.gregorianMonths;
    }
    navigationTitle(value) {
        if (!value) {
            return '';
        }
        if (this.isRangeStart(value)) {
            return this.intl.getDayJsValue(value).format('YYYY');
        }
        return this.abbrMonthNames2()[this.intl.getDayJsValue(value).month()];
    }
    isRangeStart(value) {
        if (!value) {
            return false;
        }
        return !this.intl.getDayJsValue(value).month();
    }
    title(current) {
        return `${this.abbrMonthNames2()[this.intl.getDayJsValue(current).month()]} ${this.intl.getDayJsValue(current).format('YYYY')}`;
    }
    skip(value, min) {
        const diff = this.intl.getDayJsValue(value).endOf('month').diff(this.intl.getDayJsValue(min).startOf('month'), 'month');
        return diff;
    }
    rowLength(options = {}) {
        return CELLS_LENGTH$1 + (options['prependCell'] ? 1 : 0);
    }
    total(min, max) {
        return dayjs(max).diff(min, 'month') + 1;
    }
    beginningOfPeriod(date) {
        if (!date) {
            return date;
        }
        return this.intl.getDayJsValue(date).startOf('month').toDate();
    }
    datesList(start, count) {
        return range(0, count).map(i => addMonths(start, i, this.intl.localeIdByDatePickerType));
    }
    data(options) {
        const { cellUID, focusedDate, isActiveView, max, min, selectedDate, selectionRange = [], viewDate, isDateDisabled = () => false } = options;
        if (!viewDate) {
            return EMPTY_DATA$1;
        }
        const dateValue = this.intl.getDayJsValue(viewDate).toDate();
        const firstMonthDate = firstDayOfMonth(dateValue, this.intl.localeIdByDatePickerType);
        const firstMonthDay = getDate(firstMonthDate);
        const lastMonthDate = lastDayOfMonth(dateValue, this.intl.localeIdByDatePickerType);
        const lastMonthDay = getDate(lastMonthDate);
        const backward = -1;
        const isSelectedDateInRange = dayjs(selectedDate).isBetween(min, max);
        const date = dayOfWeek(firstMonthDate, this.intl.firstDay(), backward);
        const cells = range(0, CELLS_LENGTH$1);
        // console.log('console', this.intl.firstDay())
        const today = getToday();
        return range(0, ROWS_LENGTH$1).map(rowOffset => {
            const baseDate = addDays(date, rowOffset * CELLS_LENGTH$1);
            return cells.map(cellOffset => {
                const cellDate = this['normalize'](addDays(baseDate, cellOffset), min, max);
                const cellDay = getDate(cellDate);
                const otherMonth = cellDay < firstMonthDay || cellDay > lastMonthDay;
                const outOfRange = cellDate < min || cellDate > max;
                if (outOfRange) {
                    return null;
                }
                const isRangeStart = this.isEqual(cellDate, selectionRange.start);
                const isRangeEnd = this.isEqual(cellDate, selectionRange.end);
                const isInMiddle = !isRangeStart && !isRangeEnd;
                const isRangeMid = isInMiddle && isInSelectionRange(cellDate, selectionRange);
                return {
                    formattedValue: this.value(cellDate),
                    id: `${cellUID}${cellDate.getTime()}`,
                    isFocused: this.isEqual(cellDate, focusedDate),
                    isSelected: isActiveView && isSelectedDateInRange && this.isEqual(cellDate, selectedDate),
                    isWeekend: this.isWeekend(cellDate),
                    isRangeStart,
                    isRangeMid,
                    isRangeEnd,
                    isRangeSplitStart: isRangeMid && this.isEqual(cellDate, firstMonthDate),
                    isRangeSplitEnd: isRangeMid && this.isEqual(cellDate, lastMonthDate),
                    isToday: this.isEqual(cellDate, today),
                    title: this.cellTitle(cellDate),
                    value: cellDate,
                    isDisabled: isDateDisabled(cellDate),
                    isOtherMonth: otherMonth
                };
            });
        });
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliMonthViewService, deps: [{ token: IntlService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliMonthViewService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliMonthViewService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }] }] });

class JalaliWeekNamesService extends WeekNamesService {
    _intlService;
    constructor(_intlService) {
        super(_intlService);
        this._intlService = _intlService;
    }
    getWeekNames(includeWeekNumber, nameType) {
        return super.getWeekNames(includeWeekNumber, nameType);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliWeekNamesService, deps: [{ token: i1.IntlService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliWeekNamesService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliWeekNamesService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i1.IntlService }] });

const EMPTY_DATA = [[]];
const CELLS_LENGTH = 4;
const ROWS_LENGTH = 3;

class JalaliYearViewService extends YearViewService {
    intl;
    constructor(intl) {
        super(intl);
        this.intl = intl;
    }
    abbrMonthNames2() {
        if (this.intl.isJalali) {
            return dayjs()['$locale']().jmonths;
        }
        return this.intl.getDayJsValue().localeData().monthsShort();
    }
    data(options) {
        const { cellUID, focusedDate, isActiveView, max, min, selectedDate, selectionRange = EMPTY_SELECTIONRANGE, viewDate } = options;
        if (!viewDate) {
            return EMPTY_DATA;
        }
        const months = this.abbrMonthNames2();
        const isSelectedDateInRange = dayjs(selectedDate).isBetween(min, max);
        //firstMonthOfYear
        const firstDate = this.intl.getDayJsValue(viewDate).startOf('year').add(this.intl.getDayJsValue(viewDate).date() - 1, 'day').toDate();
        const lastDate = this.intl.getDayJsValue(viewDate).endOf('year').add(-1, 'month').add(this.intl.getDayJsValue(viewDate).date(), 'day').toDate();
        const currentYear = this.intl.getDayJsValue(firstDate).year();
        const cells = range(0, CELLS_LENGTH);
        const today = getToday();
        const xxx = range(0, ROWS_LENGTH).map(rowOffset => {
            const baseDate = addMonths$1(firstDate, rowOffset * CELLS_LENGTH);
            return cells.map(cellOffset => {
                const cellDate = this['normalize'](addMonths$1(baseDate, cellOffset), min, max);
                const changedYear = currentYear < this.intl.getDayJsValue(cellDate).year();
                if (!dayjs(cellDate).isBetween(min, max)) {
                    return null;
                }
                if (changedYear) {
                    return null;
                }
                const isRangeStart = this.isEqual(cellDate, selectionRange.start);
                const isRangeEnd = this.isEqual(cellDate, selectionRange.end);
                const isInMiddle = !isRangeStart && !isRangeEnd;
                const isRangeMid = isInMiddle && isInSelectionRange(cellDate, selectionRange);
                return {
                    formattedValue: months[this.intl.getDayJsValue(cellDate).month()],
                    id: `${cellUID}${cellDate.getTime()}`,
                    isFocused: this.isEqual(cellDate, focusedDate),
                    isSelected: isActiveView && isSelectedDateInRange && this.isEqual(cellDate, selectedDate),
                    isWeekend: false,
                    isRangeStart,
                    isRangeMid,
                    isRangeEnd,
                    isRangeSplitEnd: isRangeMid && this.isEqual(cellDate, lastDate),
                    isRangeSplitStart: isRangeMid && this.isEqual(cellDate, firstDate),
                    isToday: this.isEqual(cellDate, today),
                    title: this.cellTitle(cellDate),
                    value: cellDate
                };
            });
        });
        return xxx;
    }
    title(current) {
        return `${this.intl.getDayJsValue(current).format('YYYY')}`;
    }
    navigationTitle(value) {
        return `${this.intl.getDayJsValue(value).format('YYYY')}`;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliYearViewService, deps: [{ token: IntlService }], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliYearViewService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: JalaliYearViewService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }] }] });

const Providers = [
    JalaliCenturyViewService,
    JalaliDecadeViewService,
    JalaliYearViewService,
    JalaliMonthViewService,
    JalaliWeekNamesService,
    { provide: IntlService, useClass: JalaliCldrIntlService, }, // ...getDeps(JalaliCldrIntlService)
    { provide: CldrIntlService, useClass: JalaliCldrIntlService, }, // ...getDeps(JalaliCldrIntlService)
    { provide: CenturyViewService, useClass: JalaliCenturyViewService, }, // ...getDeps(JalaliCenturyViewService)
    { provide: DecadeViewService, useClass: JalaliDecadeViewService, }, // ...getDeps(JalaliDecadeViewService)
    { provide: YearViewService, useClass: JalaliYearViewService, }, // ...getDeps(JalaliYearViewService)
    { provide: WeekNamesService, useClass: JalaliWeekNamesService, }, // ...getDeps(JalaliWeekNamesService)
    { provide: MonthViewService, useClass: JalaliMonthViewService, }, // ...getDeps(JalaliMonthViewService)
    { provide: 'HeaderTitleTemplate', useFactory: HeaderTitleTemplateFactory, deps: [EnvironmentInjector] },
];
var CalendarViewEnum;
(function (CalendarViewEnum) {
    CalendarViewEnum[CalendarViewEnum["month"] = 0] = "month";
    CalendarViewEnum[CalendarViewEnum["year"] = 1] = "year";
    CalendarViewEnum[CalendarViewEnum["decade"] = 2] = "decade";
    CalendarViewEnum[CalendarViewEnum["century"] = 3] = "century";
})(CalendarViewEnum || (CalendarViewEnum = {}));
const services = {
    [CalendarViewEnum.month]: JalaliMonthViewService,
    [CalendarViewEnum.year]: JalaliYearViewService,
    [CalendarViewEnum.decade]: JalaliDecadeViewService,
    [CalendarViewEnum.century]: JalaliCenturyViewService
};
function getDeps(srv) {
    return { useFactory: useExistingIfExist, deps: [[new Optional(), new SkipSelf(), srv], srv] };
}
function useExistingIfExist(oldService, newService) {
    if (oldService)
        return oldService;
    return newService;
}

// tslint:disable-next-line:no-string-literal
NavigationComponent.prototype['intlChange'] = function () {
    this.cdr.markForCheck();
};
class KendoDatePickerDirective {
    headerTitleTemplate;
    intl;
    cdr;
    viewContainerRef;
    hostComponent;
    constructor(headerTitleTemplate, intl, hostIntlService, cdr, viewContainerRef) {
        this.headerTitleTemplate = headerTitleTemplate;
        this.intl = intl;
        this.cdr = cdr;
        this.viewContainerRef = viewContainerRef;
        this.setHostComponent();
        hostIntlService.changes.pipe(debounceTime(30)).subscribe(x => {
            intl.changeLocaleId(hostIntlService.localeId);
            intl.changeType(hostIntlService.datePickerType);
            this.cdr.detectChanges();
        });
    }
    setHostComponent() {
        this.hostComponent = this.viewContainerRef['_hostLView'].find(x => (x?.element || x?.wrapper)?.nativeElement === this.viewContainerRef.element.nativeElement);
        if (!this.hostComponent) {
            debugger;
        }
        this.init();
    }
    init(hostComponent = this.hostComponent) {
        // debugger
        this.setHeaderTitleTemplate(hostComponent);
        // this.setBusService(hostComponent);
        // this.initCalendar(hostComponent);
        // this.initDateInput(hostComponent);
        // this.initDatePicker(hostComponent);
    }
    initDatePicker(hostComponent = this.hostComponent) {
        if (hostComponent.wrapper?.nativeElement.tagName !== 'KENDO-DATEPICKER')
            return;
        hostComponent.open.subscribe(x => {
            setTimeout(() => {
                this.init(hostComponent.calendar);
                this.populateCalendar(hostComponent.calendar);
                const intl = hostComponent.calendar.bus.service(hostComponent.calendar.activeViewEnum)._intlService;
                intl.$calendarType.pipe(debounceTime(10)).subscribe(x => {
                    hostComponent.calendar.onResize();
                });
                hostComponent.calendar.onResize();
                if (hostComponent?.calendar?.monthView)
                    hostComponent.calendar.monthView.headerComponent.title = hostComponent.calendar.monthView.headerComponent.getTitle();
            });
        });
    }
    initDateInput(hostComponent = this.hostComponent) {
        if (hostComponent.wrapper?.nativeElement.tagName !== 'KENDO-DATEINPUT')
            return;
    }
    initCalendar(hostComponent = this.hostComponent) {
        if (this.viewContainerRef.element.nativeElement.tagName !== 'kendo-calendar')
            return;
        this.populateCalendar(hostComponent);
    }
    populateCalendar(hostComponent) {
        const oldNgOnInit = hostComponent.ngOnInit;
        hostComponent.ngOnInit = function () {
            oldNgOnInit.call(this);
            const intl = this.bus.service(this.activeViewEnum)._intlService;
            intl.$calendarType.pipe(debounceTime(10)).subscribe(x => {
                this.onResize();
            });
        };
    }
    setHeaderTitleTemplate(hostComponent = this.hostComponent) {
        if (!Object.hasOwn(hostComponent, 'headerTitleTemplate')) {
            return;
        }
        if (hostComponent.headerTitleTemplate)
            return;
        setTimeout(() => {
            hostComponent.headerTitleTemplate = this.headerTitleTemplate;
            hostComponent.cdr.detectChanges();
        });
    }
    setBusService(hostComponent = this.hostComponent) {
        if (!hostComponent.bus) {
            return;
        }
        hostComponent.bus.service = (view) => {
            return this.viewContainerRef.injector.get(services[view]);
        };
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoDatePickerDirective, deps: [{ token: 'HeaderTitleTemplate' }, { token: IntlService, self: true }, { token: IntlService, skipSelf: true }, { token: i0.ChangeDetectorRef }, { token: i0.ViewContainerRef }], target: i0.ɵɵFactoryTarget.Directive });
    static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "19.0.6", type: KendoDatePickerDirective, isStandalone: true, selector: "kendo-datepicker,kendo-datetimepicker,kendo-calendar,kendo-timepicker,kendo-multiviewcalendar,kendo-dateinput", providers: [
            ...Providers
        ], ngImport: i0 });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoDatePickerDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: 'kendo-datepicker,kendo-datetimepicker,kendo-calendar,kendo-timepicker,kendo-multiviewcalendar,kendo-dateinput',
                    providers: [
                        ...Providers
                    ]
                }]
        }], ctorParameters: () => [{ type: i0.TemplateRef, decorators: [{
                    type: Inject,
                    args: ['HeaderTitleTemplate']
                }] }, { type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }, {
                    type: Self
                }] }, { type: JalaliCldrIntlService, decorators: [{
                    type: Inject,
                    args: [IntlService]
                }, {
                    type: SkipSelf
                }] }, { type: i0.ChangeDetectorRef }, { type: i0.ViewContainerRef }] });

String.prototype.toPerNumber = function () {
    return this.replace(/\d/g, (match) => {
        return enToPerNumberMap[match] || match;
    });
};
String.prototype.toEnNumber = function () {
    return this.replace(/[۰-۹]/g, d => d.charCodeAt(0) - 1776)
        .replace(/[٠-٩]/g, d => d.charCodeAt(0) - 1632);
};
String.prototype.toMomentDateTimeFormat = function () {
    let x = this.replace(/d/g, 'D')
        .replace(/aa/ig, (m) => m[0])
        .replace(/_/g, '/')
        .replace(/[y]{1,}/, 'YYYY');
    return x;
};
const enToPerNumberMap = {
    1: '١',
    2: '٢',
    3: '٣',
    4: '٤',
    5: '٥',
    6: '٦',
    7: '٧',
    8: '٨',
    9: '٩',
    0: '٠'
};
const perToEnNumberMap = {
    '١': '1',
    '٢': '2',
    '٣': '3',
    '٤': '4',
    '٥': '5',
    '٦': '6',
    '٧': '7',
    '٨': '8',
    '٩': '9',
    '٠': '0'
};

dayjs.extend(isBetween);
dayjs.extend(localeData);
dayjs.extend(updateLocale);
dayjs.extend(jalaliday);
const meridiem = (hour) => {
    return hour > 12 ? 'ب.ظ' : 'ق.ظ';
};
dayjs.updateLocale('fa', {
    meridiem
});
dayjs.updateLocale('fa-IR', {
    meridiem
});
if (typeof window !== 'undefined') {
    window['dayjs'] = dayjs;
}
setData({
    name: "fa",
    likelySubtags: {
        fa: "fa-Arab-IR"
    },
    identity: {
        language: "fa"
    },
    territory: "IR",
    calendar: {
        patterns: {
            d: "y/M/d",
            D: "EEEE d MMMM y",
            m: "d LLL",
            M: "d LLLL",
            y: "MMM y",
            Y: "MMMM y",
            F: "a h:mm:ss EEEE d MMMM y",
            g: "a h:mm y/M/d",
            G: "a h:mm:ss y/M/d",
            t: "a h:mm",
            T: "a h:mm:ss",
            s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
            u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
        },
        dateTimeFormats: {
            full: "{1}، ساعت {0}",
            long: "{1}، ساعت {0}",
            medium: "{1}،‏ {0}",
            short: "{1}،‏ {0}",
            availableFormats: {
                Bh: "h B",
                Bhm: "h:mm B",
                Bhms: "h:mm:ss B",
                d: "d",
                E: "ccc",
                EBhm: "E h:mm B",
                EBhms: "E h:mm:ss B",
                Ed: "E d",
                Ehm: "E h:mm a",
                EHm: "E H:mm",
                Ehms: "E h:mm:ss a",
                EHms: "E H:mm:ss",
                Gy: "y G",
                GyMMM: "MMM y G",
                GyMMMd: "d MMM y G",
                GyMMMEd: "E d MMM y G",
                h: "h a",
                H: "H",
                HHmmZ: "HH:mm (Z)",
                hm: "h:mm a",
                Hm: "H:mm",
                hms: "h:mm:ss a",
                Hms: "H:mm:ss",
                hmsv: "h:mm:ss a v",
                Hmsv: "H:mm:ss v",
                hmv: "h:mm a v",
                Hmv: "H:mm v",
                M: "L",
                Md: "M/d",
                MEd: "E M/d",
                MMM: "LLL",
                MMMd: "d LLL",
                MMMEd: "E d LLL",
                MMMMd: "d LLLL",
                MMMMEd: "E d LLLL",
                "MMMMW-count-one": "هفتهٔ Wم LLLL",
                "MMMMW-count-other": "هفتهٔ Wم LLLL",
                mmss: "mm:ss",
                ms: "m:ss",
                y: "y",
                yM: "y/M",
                yMd: "y/M/d",
                yMEd: "E y/M/d",
                yMMM: "MMM y",
                yMMMd: "d MMM y",
                yMMMEd: "E d MMM y",
                yMMMM: "MMMM y",
                yMMMMEEEEd: "EEEE d MMMM y",
                yQQQ: "QQQQ y",
                yQQQQ: "QQQQ y",
                "yw-count-one": "هفتهٔ wم Y",
                "yw-count-other": "هفتهٔ wم Y"
            }
        },
        timeFormats: {
            full: "H:mm:ss (zzzz)",
            long: "H:mm:ss (z)",
            medium: "H:mm:ss",
            short: "H:mm"
        },
        dateFormats: {
            full: "EEEE d MMMM y",
            long: "d MMMM y",
            medium: "d MMM y",
            short: "y/M/d"
        },
        days: {
            format: {
                abbreviated: [
                    "یکشنبه",
                    "دوشنبه",
                    "سه‌شنبه",
                    "چهارشنبه",
                    "پنجشنبه",
                    "جمعه",
                    "شنبه"
                ],
                narrow: [
                    "ی",
                    "د",
                    "س",
                    "چ",
                    "پ",
                    "ج",
                    "ش"
                ],
                short: [
                    "۱ش",
                    "۲ش",
                    "۳ش",
                    "۴ش",
                    "۵ش",
                    "ج",
                    "ش"
                ],
                wide: [
                    "یکشنبه",
                    "دوشنبه",
                    "سه‌شنبه",
                    "چهارشنبه",
                    "پنجشنبه",
                    "جمعه",
                    "شنبه"
                ]
            },
            "stand-alone": {
                abbreviated: [
                    "یکشنبه",
                    "دوشنبه",
                    "سه‌شنبه",
                    "چهارشنبه",
                    "پنجشنبه",
                    "جمعه",
                    "شنبه"
                ],
                narrow: [
                    "ی",
                    "د",
                    "س",
                    "چ",
                    "پ",
                    "ج",
                    "ش"
                ],
                short: [
                    "۱ش",
                    "۲ش",
                    "۳ش",
                    "۴ش",
                    "۵ش",
                    "ج",
                    "ش"
                ],
                wide: [
                    "یکشنبه",
                    "دوشنبه",
                    "سه‌شنبه",
                    "چهارشنبه",
                    "پنجشنبه",
                    "جمعه",
                    "شنبه"
                ]
            }
        },
        months: {
            format: {
                abbreviated: [
                    "ژانویهٔ",
                    "فوریهٔ",
                    "مارس",
                    "آوریل",
                    "مهٔ",
                    "ژوئن",
                    "ژوئیهٔ",
                    "اوت",
                    "سپتامبر",
                    "اکتبر",
                    "نوامبر",
                    "دسامبر"
                ],
                narrow: [
                    "ژ",
                    "ف",
                    "م",
                    "آ",
                    "م",
                    "ژ",
                    "ژ",
                    "ا",
                    "س",
                    "ا",
                    "ن",
                    "د"
                ],
                wide: [
                    "ژانویهٔ",
                    "فوریهٔ",
                    "مارس",
                    "آوریل",
                    "مهٔ",
                    "ژوئن",
                    "ژوئیهٔ",
                    "اوت",
                    "سپتامبر",
                    "اکتبر",
                    "نوامبر",
                    "دسامبر"
                ]
            },
            "stand-alone": {
                abbreviated: [
                    "ژانویه",
                    "فوریه",
                    "مارس",
                    "آوریل",
                    "مه",
                    "ژوئن",
                    "ژوئیه",
                    "اوت",
                    "سپتامبر",
                    "اکتبر",
                    "نوامبر",
                    "دسامبر"
                ],
                narrow: [
                    "ژ",
                    "ف",
                    "م",
                    "آ",
                    "م",
                    "ژ",
                    "ژ",
                    "ا",
                    "س",
                    "ا",
                    "ن",
                    "د"
                ],
                wide: [
                    "ژانویه",
                    "فوریه",
                    "مارس",
                    "آوریل",
                    "مه",
                    "ژوئن",
                    "ژوئیه",
                    "اوت",
                    "سپتامبر",
                    "اکتبر",
                    "نوامبر",
                    "دسامبر"
                ]
            }
        },
        quarters: {
            format: {
                abbreviated: [
                    "س‌م۱",
                    "س‌م۲",
                    "س‌م۳",
                    "س‌م۴"
                ],
                narrow: [
                    "۱",
                    "۲",
                    "۳",
                    "۴"
                ],
                wide: [
                    "سه‌ماههٔ اول",
                    "سه‌ماههٔ دوم",
                    "سه‌ماههٔ سوم",
                    "سه‌ماههٔ چهارم"
                ]
            },
            "stand-alone": {
                abbreviated: [
                    "س‌م۱",
                    "س‌م۲",
                    "س‌م۳",
                    "س‌م۴"
                ],
                narrow: [
                    "۱",
                    "۲",
                    "۳",
                    "۴"
                ],
                wide: [
                    "سه‌ماههٔ اول",
                    "سه‌ماههٔ دوم",
                    "سه‌ماههٔ سوم",
                    "سه‌ماههٔ چهارم"
                ]
            }
        },
        dayPeriods: {
            format: {
                abbreviated: {
                    am: "ق.ظ.",
                    pm: "ب.ظ.",
                    morning1: "بامداد",
                    morning2: "صبح",
                    afternoon1: "ظهر",
                    afternoon2: "عصر",
                    night1: "شب",
                    night2: "نیمه‌شب"
                },
                narrow: {
                    am: "ق",
                    pm: "ب",
                    morning1: "ب",
                    morning2: "ص",
                    afternoon1: "ظ",
                    afternoon2: "ع",
                    night1: "ش",
                    night2: "ن"
                },
                wide: {
                    am: "قبل‌ازظهر",
                    pm: "بعدازظهر",
                    morning1: "بامداد",
                    morning2: "صبح",
                    afternoon1: "ظهر",
                    afternoon2: "عصر",
                    night1: "شب",
                    night2: "نیمه‌شب"
                }
            },
            "stand-alone": {
                abbreviated: {
                    am: "ق.ظ.",
                    pm: "ب.ظ.",
                    morning1: "بامداد",
                    morning2: "صبح",
                    afternoon1: "ظهر",
                    afternoon2: "عصر",
                    night1: "شب",
                    night2: "نیمه‌شب"
                },
                narrow: {
                    am: "ق",
                    pm: "ب",
                    morning1: "ب",
                    morning2: "ص",
                    afternoon1: "ظ",
                    afternoon2: "ع",
                    night1: "ش",
                    night2: "ن"
                },
                wide: {
                    am: "قبل‌ازظهر",
                    pm: "بعدازظهر",
                    morning1: "بامداد",
                    morning2: "صبح",
                    afternoon1: "ظهر",
                    afternoon2: "عصر",
                    night1: "شب",
                    night2: "نیمه‌شب"
                }
            }
        },
        eras: {
            format: {
                wide: {
                    "0": "قبل از میلاد",
                    "1": "میلادی",
                    "0-alt-variant": "قبل از دوران مشترک",
                    "1-alt-variant": "دوران مشترک"
                },
                abbreviated: {
                    "0": "ق.م.",
                    "1": "م.",
                    "0-alt-variant": "ق.د.م",
                    "1-alt-variant": "د.م."
                },
                narrow: {
                    "0": "ق",
                    "1": "م",
                    "0-alt-variant": "ق.د.م",
                    "1-alt-variant": "د.م."
                }
            }
        },
        gmtFormat: "{0} گرینویچ",
        gmtZeroFormat: "گرینویچ",
        dateFields: {
            era: {
                wide: "دوره",
                short: "دوره",
                narrow: "دوره"
            },
            year: {
                wide: "سال",
                short: "سال",
                narrow: "سال"
            },
            quarter: {
                wide: "سه‌ماهه",
                short: "سه‌ماهه",
                narrow: "سه‌ماهه"
            },
            month: {
                wide: "ماه",
                short: "ماه",
                narrow: "ماه"
            },
            week: {
                wide: "هفته",
                short: "هفته",
                narrow: "هفته"
            },
            weekOfMonth: {
                wide: "هفتهٔ ماه",
                short: "هفتهٔ ماه",
                narrow: "هفتهٔ ماه"
            },
            day: {
                wide: "روز",
                short: "روز",
                narrow: "روز"
            },
            dayOfYear: {
                wide: "روز سال",
                short: "روز سال",
                narrow: "روز سال"
            },
            weekday: {
                wide: "روز هفته",
                short: "روز هفته",
                narrow: "روز هفته"
            },
            weekdayOfMonth: {
                wide: "روز کاری ماه",
                short: "روز کاری ماه",
                narrow: "روز کاری ماه"
            },
            dayperiod: {
                short: "قبل/بعدازظهر",
                wide: "قبل/بعدازظهر",
                narrow: "قبل/بعدازظهر"
            },
            hour: {
                wide: "ساعت",
                short: "ساعت",
                narrow: "ساعت"
            },
            minute: {
                wide: "دقیقه",
                short: "دقیقه",
                narrow: "دقیقه"
            },
            second: {
                wide: "ثانیه",
                short: "ثانیه",
                narrow: "ثانیه"
            },
            zone: {
                wide: "منطقهٔ زمانی",
                short: "منطقهٔ زمانی",
                narrow: "منطقهٔ زمانی"
            }
        }
    },
    firstDay: 6
});
class KendoJalaliDateInputsModule {
    constructor() {
    }
    static forRoot(configs) {
        return {
            ngModule: KendoJalaliDateInputsModule,
            providers: [
                { provide: 'CONFIGS', useValue: { ...configs } }
            ]
        };
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoJalaliDateInputsModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "19.0.6", ngImport: i0, type: KendoJalaliDateInputsModule, imports: [KendoDatePickerDirective], exports: [KendoDatePickerDirective] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoJalaliDateInputsModule, providers: [
            JalaliCenturyViewService,
            JalaliDecadeViewService,
            JalaliYearViewService,
            JalaliMonthViewService,
            JalaliWeekNamesService,
            DateTimeNumberService,
            ...Providers,
            { provide: 'CONFIGS', useValue: {} }
        ] });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.0.6", ngImport: i0, type: KendoJalaliDateInputsModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        KendoDatePickerDirective,
                    ],
                    providers: [
                        JalaliCenturyViewService,
                        JalaliDecadeViewService,
                        JalaliYearViewService,
                        JalaliMonthViewService,
                        JalaliWeekNamesService,
                        DateTimeNumberService,
                        ...Providers,
                        { provide: 'CONFIGS', useValue: {} }
                    ],
                    exports: [
                        KendoDatePickerDirective,
                    ]
                }]
        }], ctorParameters: () => [] });

const MONTH_PART_WITH_WORDS_THRESHOLD = 2;
const JS_MONTH_OFFSET = 1;
const MIN_JALALI_DATE = dayjs('0000-01-01', 'YYYY/MM/DD', 'fa');
DateInput.prototype.onElementInput = onElementInput;
DateInput.prototype.refreshElementValue = refreshElementValue;
DateObject.prototype.dateFormatString = dateFormatString;
DateObject.prototype.getTextAndFormat = getTextAndFormat;
const oldInitKendoDate = DateInputComponent.prototype['initKendoDate'];
DateInputComponent.prototype['initKendoDate'] = function () {
    const kendoDate = oldInitKendoDate.call(this);
    if (this.value) {
        setTimeout(() => {
            this.kendoDate?.refreshElementValue();
        });
    }
    return kendoDate;
};
function onElementInput(e) {
    this.triggerInput({ event: e });
    const oldElementValue = this.elementValue;
    if (!this.element || !this.dateObject) {
        return;
    }
    const switchedPartOnPreviousKeyAction = this.switchedPartOnPreviousKeyAction;
    if (this.isPasteInProgress) {
        if (this.options.allowCaretMode) {
            // pasting should leave the input with caret
            // thus allow direct input instead of selection mode
            this.resetSegmentValue = false;
        }
        this.updateOnPaste(e);
        this.isPasteInProgress = false;
        return;
    }
    const keyDownEvent = this.keyDownEvent || {};
    const isBackspaceKey = keyDownEvent.keyCode === KeyCode.BACKSPACE || keyDownEvent.key === Key.BACKSPACE;
    const isDeleteKey = keyDownEvent.keyCode === KeyCode.DELETE || keyDownEvent.key === Key.DELETE;
    const originalInteractionMode = this.interactionMode;
    if (this.options.allowCaretMode &&
        originalInteractionMode !== DateInputInteractionMode.Caret &&
        !isDeleteKey && !isBackspaceKey) {
        this.resetSegmentValue = true;
    }
    if (this.options.allowCaretMode) {
        this.interactionMode = DateInputInteractionMode.Caret;
    }
    else {
        this.interactionMode = DateInputInteractionMode.Selection;
    }
    const hasCaret = this.isInCaretMode();
    if (hasCaret && this.keyDownEvent.key === Key.SPACE) {
        // do not allow custom "holes" in the date segments
        this.restorePreviousInputEventState();
        return;
    }
    const oldExistingDateValue = this.dateObject && this.dateObject.getValue();
    const oldDateValue = this.dateObject ? this.dateObject.value : null;
    const { text: currentText, format: currentFormat } = this.dateObject.getTextAndFormat();
    this.currentFormat = currentFormat;
    let oldText = "";
    if (hasCaret) {
        if (isBackspaceKey || isDeleteKey) {
            oldText = this.previousElementValue;
        }
        else if (originalInteractionMode === DateInputInteractionMode.Caret) {
            oldText = this.previousElementValue;
        }
        else {
            oldText = currentText;
        }
    }
    else {
        oldText = currentText;
    }
    const newText = this.elementValue;
    const diff = approximateStringMatching({
        oldText: oldText.toEnNumber(),
        newText: newText.toEnNumber(),
        formatPattern: this.currentFormat,
        selectionStart: this.selection.start,
        isInCaretMode: hasCaret,
        keyEvent: this.keyDownEvent
    });
    console.log('before diff', diff[0], this.intl.service.calendarType);
    prepareDiffInJalaliMode.call(this, this.intl.service, diff);
    console.log('diff', diff[0]);
    console.log('leadingZero', this.dateObject.leadingZero);
    if (diff && diff.length && diff[0] && diff[0][1] !== Constants.formatSeparator) {
        this.switchedPartOnPreviousKeyAction = false;
    }
    if (hasCaret && (!diff || diff.length === 0)) {
        this.restorePreviousInputEventState();
        return;
    }
    else if (hasCaret && diff.length === 1) {
        if (!diff[0] || !diff[0][0]) {
            this.restorePreviousInputEventState();
            return;
        }
        else if (hasCaret && diff[0] &&
            (diff[0][0] === Constants.formatSeparator || diff[0][1] === Constants.formatSeparator)) {
            this.restorePreviousInputEventState();
            return;
        }
    }
    const navigationOnly = (diff.length === 1 && diff[0][1] === Constants.formatSeparator);
    const parsePartsResults = [];
    let switchPart = false;
    let error = null;
    if (!navigationOnly) {
        for (let i = 0; i < diff.length; i++) {
            const parsePartResult = this.intl.service.isGregorian ? this.dateObject.parsePart({
                symbol: diff[i][0],
                currentChar: diff[i][1],
                resetSegmentValue: this.resetSegmentValue,
                cycleSegmentValue: !this.isInCaretMode(),
                rawTextValue: this.element.value,
                isDeleting: isBackspaceKey || isDeleteKey,
                originalFormat: this.currentFormat
            }) : parsePart.call(this, diff);
            parsePartsResults.push(parsePartResult);
            if (!parsePartResult.value) {
                error = { type: "parse" };
            }
            switchPart = parsePartResult.switchToNext;
        }
    }
    if (!this.options.autoSwitchParts) {
        switchPart = false;
    }
    this.resetSegmentValue = false;
    const hasFixedFormat = this.options.format === this.currentFormat ||
        // all not fixed formats are 1 symbol, e.g. "d"
        (isPresent(this.options.format) && this.options.format.length > 1);
    const lastParseResult = parsePartsResults[parsePartsResults.length - 1];
    const lastParseResultHasNoValue = lastParseResult && !isPresent(lastParseResult.value);
    const parsingFailedOnDelete = (hasCaret && (isBackspaceKey || isDeleteKey) && lastParseResultHasNoValue);
    const resetPart = lastParseResult ? lastParseResult.resetPart : false;
    const newExistingDateValue = this.dateObject.getValue();
    const hasExistingDateValueChanged = !isEqual(oldExistingDateValue, newExistingDateValue);
    const newDateValue = this.dateObject.value;
    let symbolForSelection;
    const currentSelection = this.selection;
    if (hasCaret) {
        const diffChar = diff && diff.length > 0 ? diff[0][0] : null;
        const hasLeadingZero = this.dateObject.getLeadingZero()[diffChar];
        if (diff.length && diff[0][0] !== Constants.formatSeparator) {
            if (switchPart) {
                this.forceUpdateWithSelection();
                this.switchDateSegment(1);
            }
            else if (resetPart) {
                symbolForSelection = this.currentFormat[currentSelection.start];
                if (symbolForSelection) {
                    this.forceUpdate();
                    this.setSelection(this.selectionBySymbol(symbolForSelection));
                }
                else {
                    this.restorePreviousInputEventState();
                }
            }
            else if (parsingFailedOnDelete) {
                this.forceUpdate();
                if (diff.length && diff[0][0] !== Constants.formatSeparator) {
                    this.setSelection(this.selectionBySymbol(diff[0][0]));
                }
            }
            else if (lastParseResultHasNoValue) {
                if (e.data === '0' && hasLeadingZero) {
                    // do not reset element value on a leading zero
                    // wait for consecutive input to determine the value
                }
                else if (isPresent(oldExistingDateValue) && !isPresent(newExistingDateValue)) {
                    this.restorePreviousInputEventState();
                }
                else if (!isPresent(oldExistingDateValue) && isPresent(newExistingDateValue)) {
                    this.forceUpdateWithSelection();
                }
                else if (isPresent(oldExistingDateValue) && isPresent(newExistingDateValue)) {
                    if (hasExistingDateValueChanged) {
                        this.forceUpdateWithSelection();
                    }
                    else {
                        this.restorePreviousInputEventState();
                    }
                }
                else if (!isPresent(oldExistingDateValue) && !isPresent(newExistingDateValue)) {
                    this.forceUpdateWithSelection();
                }
                else if (oldDateValue !== newDateValue) {
                    // this can happen on auto correct when no valid value is parsed
                }
                else {
                    this.restorePreviousInputEventState();
                }
            }
            else {
                // the user types a valid but incomplete date (e.g. year "123" with format "yyyy")
                // let them continue typing, but refresh for not fixed formats
                if (!hasFixedFormat) {
                    this.forceUpdateWithSelection();
                }
            }
        }
        else {
            if (!this.options.autoSwitchParts && diff[0][1] === Constants.formatSeparator) {
                // do not change the selection when a separator is pressed
                // this should happen only if autoSwitchKeys contains the separator explicitly
            }
            else {
                this.setSelection(this.selectionBySymbol(diff[0][0]));
            }
        }
    }
    else if (!hasCaret) {
        this.forceUpdate();
        if (diff.length && diff[0][0] !== Constants.formatSeparator) {
            this.setSelection(this.selectionBySymbol(diff[0][0]));
        }
        if (this.options.autoSwitchParts) {
            if (navigationOnly) {
                this.resetSegmentValue = true;
                if (!switchedPartOnPreviousKeyAction) {
                    this.switchDateSegment(1);
                }
                this.switchedPartOnPreviousKeyAction = true;
            }
            else if (switchPart) {
                this.switchDateSegment(1);
                this.switchedPartOnPreviousKeyAction = true;
            }
        }
        else {
            if (lastParseResult && lastParseResult.switchToNext) {
                // the value is complete and should be switched, but the "autoSwitchParts" option prevents this
                // ensure that the segment value can be reset on next input
                this.resetSegmentValue = true;
            }
            else if (navigationOnly) {
                this.resetSegmentValue = true;
                if (!switchedPartOnPreviousKeyAction) {
                    this.switchDateSegment(1);
                }
                this.switchedPartOnPreviousKeyAction = true;
            }
        }
        if (isBackspaceKey && this.options.selectPreviousSegmentOnBackspace) {
            // kendo angular have this UX
            this.switchDateSegment(-1);
        }
    }
    this.tryTriggerValueChange({
        oldValue: oldExistingDateValue,
        event: e
    });
    this.triggerInputEnd({ event: e, error: error, oldElementValue: oldElementValue, newElementValue: this.elementValue });
    if (hasCaret) {
        // a format like "F" can dynamically change the resolved format pattern based on the value, e.g.
        // "Tuesday, February 1, 2022 3:04:05 AM" becomes
        // "Wednesday, February 2, 2022 3:04:05 AM" giving a diff of 2 ("Tuesday".length - "Wednesday".length)
        this.setTextAndFormat();
    }
}
function refreshElementValue() {
    const element = this.element;
    const format = this.isActive ? this.inputFormat : this.displayFormat;
    const { text: currentText, format: currentFormat } = this.dateObject.getTextAndFormat(format);
    this.currentFormat = currentFormat;
    this.currentText = currentText;
    const hasPlaceholder = this.options.hasPlaceholder || isPresent(this.options.placeholder);
    const showPlaceholder = !this.isActive &&
        hasPlaceholder &&
        !this.dateObject.hasValue();
    if (hasPlaceholder && isPresent(this.options.placeholder)) {
        element.placeholder = this.options.placeholder;
    }
    const newElementValue = showPlaceholder ? "" : this.currentText;
    this.previousElementValue = this.elementValue;
    console.log('newElementValue', newElementValue);
    this.setElementValue(newElementValue);
}
;
function getTextAndFormat(customFormat = "") {
    let format = customFormat || this.format;
    let text = this.intl.service.getDayJsValue(this.value)?.locale(this.intl.localeId)?.format(mapKendoFormatToDayJs(format, this.intl.service, this.value));
    const mask = this.dateFormatString(this.value, format);
    if (this.autoCorrectParts || !this._partiallyInvalidDate.startDate) {
        return this.merge(text, mask);
    }
    let partiallyInvalidText = "";
    const formattedDate = this.intl.formatDate(this.value, format, this.intl.localeId);
    const formattedDates = this.getFormattedInvalidDates(format);
    for (let i = 0; i < formattedDate.length; i++) {
        const symbol = mask.symbols[i];
        if (mask.partMap[i].type === "literal") {
            partiallyInvalidText += text[i];
        }
        else if (this.getInvalidDatePartValue(symbol)) {
            const partsForSegment = this.getPartsForSegment(mask, i);
            if (symbol === "M") {
                const datePartText = (parseToInt(this.getInvalidDatePartValue(symbol)) + JS_MONTH_OFFSET).toString();
                if (partsForSegment.length > MONTH_PART_WITH_WORDS_THRESHOLD) {
                    partiallyInvalidText += formattedDates[symbol][i];
                }
                else {
                    if (this.getInvalidDatePartValue(symbol)) {
                        const formattedDatePart = padZero(partsForSegment.length - datePartText.length) + datePartText;
                        partiallyInvalidText += formattedDatePart;
                        // add -1 as the first character in the segment is at index i
                        i += partsForSegment.length - 1;
                    }
                    else {
                        partiallyInvalidText += formattedDates[symbol][i];
                    }
                }
            }
            else {
                if (this.getInvalidDatePartValue(symbol)) {
                    const datePartText = this.getInvalidDatePartValue(symbol).toString();
                    const formattedDatePart = padZero(partsForSegment.length - datePartText.length) + datePartText;
                    partiallyInvalidText += formattedDatePart;
                    // add -1 as the first character in the segment is at index i
                    i += partsForSegment.length - 1;
                }
                else {
                    partiallyInvalidText += formattedDates[symbol][i];
                }
            }
        }
        else {
            partiallyInvalidText += text[i];
        }
    }
    text = partiallyInvalidText;
    const result = this.merge(text, mask);
    return result;
}
function dateFormatString(date, format) {
    var dateFormatParts = this.intl.splitDateFormat(format, this.intl.service.localeIdByDatePickerType);
    var parts = [];
    var partMap = [];
    for (var i = 0; i < dateFormatParts.length; i++) {
        let partLength = this.intl.service.getDayJsValue(date)?.format(dateFormatParts[i].pattern.toMomentDateTimeFormat()).length || 0;
        while (partLength > 0) {
            parts.push(this.symbols[dateFormatParts[i].pattern[0]] || Constants.formatSeparator);
            partMap.push(dateFormatParts[i]);
            partLength--;
        }
    }
    var returnValue = new Mask();
    returnValue.symbols = parts.join('');
    returnValue.partMap = partMap;
    return returnValue;
}
;
function mapKendoFormatToDayJs(format, i18n, dt) {
    // if (format === 'd')
    //   format = i18n.isJalali ? 'y_M_d' : 'M_d_y';
    // else if (format === 'g')
    //   format = i18n.isJalali ? 'y_M_d h_mm_aa' : 'M_d_y h_mm_aa';
    // else if (format === 't')
    //   format = 'h:mm A';
    return convertKendoToDayjsFormat(format, i18n.localeId); // (mapFormatToDayJs(format, dt));
}
function mapFormatToDayJs(value, dt) {
    return value.replace('h_mm_aa', 'h:mm A').replaceAll('_', '/').replaceAll('y', dt.getFullYear() < 623 ? '0' : 'YYYY').replaceAll('d', 'D').replaceAll('aa', 'a');
}
function prepareDiffInJalaliMode(intl, diff) {
    if (!intl.isJalali) {
        return;
    }
    if (!this.elementValue || !this.dateObject.hasValue()) {
        this.dateObject.date = false;
        this.dateObject.year = false;
        this.dateObject.month = false;
        this.dateObject = this.getDateObject((MIN_JALALI_DATE.clone().toDate()));
    }
    if (!this.elementValue)
        return;
    const dt = intl.getDayJsValue(this.dateObject.value, 'fa');
    if (!dt)
        return;
    // if (debuggerCounter(3)) { }
    diff.forEach((d) => {
        if (!d[0])
            return;
        if (d[0] === 'M') {
            this.dateObject.month = d[1] != '';
            if (d[1] === '') {
                existInputs.M = false;
                this.dateObject = this.getDateObject(dt.month((+d[1])).toDate());
                return;
            }
            let month = d[1];
            if (existInputs.M) {
                month = +(dt.month() + 1) + d[1];
                resetExistingInputs();
            }
            else {
                existInputs.M = true;
                if (month === '0') {
                    existInputs.M = false;
                    this.dateObject.month = false;
                    this.dateObject.value = dt.month(0).toDate();
                    this.dateObject.leadingZero = { [d[0]]: 1 };
                    return;
                }
            }
            this.dateObject.value = (dt.set('month', month - 1).toDate());
            d[1] = '' + (dt.locale('en').month() + 1);
            return;
        }
        else if (d[0].toLocaleLowerCase() === 'd') {
            if (d[1] === '') {
                existInputs.d = false;
                this.dateObject = this.getDateObject(dt.date((+d[1])).toDate());
                return;
            }
            this.dateObject.date = true;
            let day = d[1];
            if (existInputs.d) {
                day = +(dt.date()) + d[1];
                resetExistingInputs();
            }
            else {
                existInputs.d = true;
                if (day === '0') {
                    existInputs.d = false;
                    this.dateObject.date = false;
                    this.dateObject.leadingZero = { d: 1 };
                    this.dateObject.value = dt.day(1).toDate();
                    return;
                }
            }
            this.dateObject.value = (dt.set('date', +day).toDate());
            d[1] = '' + (dt.locale('en').date());
            return;
        }
        else if (d[0].toLocaleLowerCase() === 'y') {
            d[1] = prepareYearValue.call(this, d, dt);
        }
        else if (d[0].toLocaleLowerCase() === 'h') {
            d[1] = prepareHourValue.call(this, d, dt);
        }
        else if (d[0].toLocaleLowerCase() === 'm') {
            d[1] = prepareMinuteValue.call(this, d, dt);
        }
        else if (d[0].toLocaleLowerCase() === 's') {
            d[1] = prepareSecondValue.call(this, d, dt);
        }
    });
}
function prepareSecondValue(diff, dt) {
    diff[2] = false;
    this.dateObject.seconds = false;
    const seconds = diff[1];
    const format = diff[0];
    if (seconds === '') {
        existInputs.s = false;
        this.dateObject = this.getDateObject(dt.second((+seconds)).toDate());
        return '';
    }
    this.dateObject.seconds = true;
    // if (!existInputs.y && year === '0') {
    //   existInputs.y = false;
    //   this.dateObject.year = false;
    //   return;
    // }
    if (!existInputs.s || dt.format(format).length > 1) {
        existInputs.s = true;
        this.dateObject = this.getDateObject(dt.second((+seconds)).toDate());
        return seconds === '' ? '' : dt.format(format);
    }
    this.dateObject.value = dt.second(+(dt.second() + seconds)).toDate();
    if (dt.format(format).length > 1) {
        resetExistingInputs();
        diff[2] = true;
    }
    return dt.format(format);
}
function prepareMinuteValue(diff, dt) {
    diff[2] = false;
    this.dateObject.hours = false;
    const minutes = diff[1];
    const format = diff[0];
    if (minutes === '') {
        existInputs.m = false;
        this.dateObject = this.getDateObject(dt.minute((+minutes)).toDate());
        return '';
    }
    this.dateObject.hours = true;
    // if (!existInputs.y && year === '0') {
    //   existInputs.y = false;
    //   this.dateObject.year = false;
    //   return;
    // }
    if (!existInputs.m || dt.format(format).length > 1) {
        existInputs.m = true;
        this.dateObject = this.getDateObject(dt.minute((+minutes)).toDate());
        return minutes === '' ? '' : dt.format(format);
    }
    this.dateObject.value = dt.minute(+(dt.minute() + minutes)).toDate();
    if (dt.format(format).length > 1) {
        resetExistingInputs();
        diff[2] = true;
    }
    return dt.format(format);
}
function prepareHourValue(diff, dt) {
    diff[2] = false;
    this.dateObject.hours = false;
    const hours = diff[1];
    const format = diff[0];
    if (hours === '') {
        existInputs.h = false;
        this.dateObject = this.getDateObject(dt.hour((+hours)).toDate());
        return '';
    }
    this.dateObject.hours = true;
    // if (!existInputs.y && year === '0') {
    //   existInputs.y = false;
    //   this.dateObject.year = false;
    //   return;
    // }
    if (!existInputs.h || dt.format(format).length > 1) {
        existInputs.h = true;
        this.dateObject = this.getDateObject(dt.hour((+hours)).toDate());
        return hours === '' ? '' : dt.format(format);
    }
    this.dateObject.value = dt.hour(+(dt.hour() + hours)).toDate();
    if (dt.format(format).length > 1) {
        resetExistingInputs();
        diff[2] = true;
    }
    return dt.format(format);
}
function prepareYearValue(diff, dt) {
    diff[2] = false;
    this.dateObject.year = false;
    const year = diff[1];
    if (year === '') {
        existInputs.y = false;
        this.dateObject = this.getDateObject(dt.year((+year)).toDate());
        return '';
    }
    this.dateObject.year = true;
    // if (!existInputs.y && year === '0') {
    //   existInputs.y = false;
    //   this.dateObject.year = false;
    //   return '0';
    // }
    if (!existInputs.y || ('' + dt.year()).length > 3) {
        existInputs.y = true;
        this.dateObject = this.getDateObject(dt.year((+year) || 1).toDate());
        return year === '' ? '0' : year === '0' ? '0' : '' + dt.year();
    }
    this.dateObject.value = dt.year(+(dt.year() + year)).toDate();
    if (('' + dt.year()).length > 3) {
        resetExistingInputs();
        diff[2] = true;
    }
    return '' + dt.year();
}
function resetExistingInputs() {
    existInputs.M = false;
    existInputs.d = false;
    existInputs.y = false;
    existInputs.h = false;
    existInputs.m = false;
    existInputs.s = false;
    existInputs.a = false;
}
const existInputs = {
    M: false,
    d: false,
    y: false,
    h: false,
    m: false,
    s: false,
    a: false
};
function parsePart(diff) {
    const value = this.dateObject.value;
    const dt = this.intl.service.getDayJsValue(this.dateObject.value);
    let switchToNext = false;
    if (!diff[0]?.[0])
        return {
            hasInvalidDatePart: false,
            resetPart: false,
            switchToNext: false,
            value
        };
    const target = diff[0][0].toLocaleLowerCase();
    if (diff[0][0] === 'M') {
        switchToNext = dt.month() > 0;
    }
    else if (target === 'd') {
        switchToNext = dt.date() > 3;
    }
    else if (target === 'y') {
        switchToNext = dt.year() > 1000;
    }
    else if (target === 'a') {
        switchToNext = true;
    }
    else if (diff[0][0] === 'h') {
        switchToNext = dt.hour() > 1;
    }
    else if (diff[0][0] === 'H') {
        switchToNext = dt.hour() > 5;
    }
    else if (diff[0][0] === 'm') {
        switchToNext = dt.minute() > 5;
    }
    else if (diff[0][0] === 's') {
        switchToNext = dt.second() > 5;
    }
    return {
        hasInvalidDatePart: false,
        resetPart: true,
        switchToNext,
        value
    };
}
function convertKendoToDayjsFormat(kendoFormat, localeId) {
    const aliasFormats = localeData$1(localeId).calendar.patterns;
    const kendoToDayjsMap = {
        'yyyy': 'YYYY',
        'yy': 'YY',
        'y': 'YYYY',
        'yyy': 'YYY',
        'dd': 'DD',
        'd': 'D',
        'tt': 'A',
        'fff': 'SSS' // اگر نیاز به پشتیبانی از میلیثانیه دارید,
    };
    const regexPattern = Object.keys(kendoToDayjsMap)
        .sort((a, b) => b.length - a.length)
        .map(escapeRegExp)
        .join('|');
    const regex = new RegExp(regexPattern, 'g');
    return (aliasFormats[kendoFormat] || kendoFormat).replace(regex, match => kendoToDayjsMap[match]);
}
function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var dateInput_component = {};

/*
 * Public API Surface of kendo-jalali-date-inputs
 */

/**
 * Generated bundle index. Do not edit.
 */

export { DatePickerType, JalaliCldrIntlService, KendoDatePickerDirective, KendoJalaliDateInputsModule };
//# sourceMappingURL=tiampersian-kendo-jalali-date-inputs.mjs.map