"use strict";
/* eslint-disable jsx-a11y/control-has-associated-label */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Calendar = void 0;
/* eslint-disable jsx-a11y/click-events-have-key-events */
var react_1 = __importDefault(require("react"));
var bem_react_classname_1 = require("bem-react-classname");
var difference_in_months_1 = __importDefault(require("date-fns/difference_in_months"));
var difference_in_milliseconds_1 = __importDefault(require("date-fns/difference_in_milliseconds"));
var start_of_day_1 = __importDefault(require("date-fns/start_of_day"));
var start_of_month_1 = __importDefault(require("date-fns/start_of_month"));
var add_days_1 = __importDefault(require("date-fns/add_days"));
var add_years_1 = __importDefault(require("date-fns/add_years"));
var sub_years_1 = __importDefault(require("date-fns/sub_years"));
var format_1 = __importDefault(require("date-fns/format"));
var is_same_month_1 = __importDefault(require("date-fns/is_same_month"));
var set_month_1 = __importDefault(require("date-fns/set_month"));
var set_year_1 = __importDefault(require("date-fns/set_year"));
var end_of_month_1 = __importDefault(require("date-fns/end_of_month"));
var each_day_1 = __importDefault(require("date-fns/each_day"));
var lodash_sortedindexof_1 = __importDefault(require("lodash.sortedindexof"));
var lodash_sortedindexby_1 = __importDefault(require("lodash.sortedindexby"));
var icons_glyph_1 = require("@alfalab/icons-glyph");
var icons_classic_1 = require("@alfalab/icons-classic");
var keyboard_code_1 = __importDefault(require("../lib/keyboard-code"));
var performance_1 = __importDefault(require("../performance"));
var utils_1 = require("./utils");
var date_utils_1 = require("../lib/date-utils");
var window_1 = require("../lib/window");
var cn_1 = require("../cn");
var DAYS_IN_WEEK = 7;
var EARLY_YEARS_LIMIT = 100;
var LATER_YEARS_LIMIT = 1;
var TOTAL_WEEK_NUMBER = 6;
var SUNDAY_INDEX = 6;
var WITHOUT_TIME_FORMAT = 'YYYY-MM-DD';
/**
 * Компонент календаря.
 */
var Calendar = /** @class */ (function (_super) {
    __extends(Calendar, _super);
    function Calendar() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.cn = bem_react_classname_1.createCn('calendar');
        _this.state = {
            month: start_of_month_1.default(new Date()),
        };
        _this.selectedYearRef = react_1.default.createRef();
        _this.yearsListRef = react_1.default.createRef();
        _this.blurTimeoutId = null;
        _this.years = [];
        _this.handleMonthClick = function () {
            _this.setState({
                // eslint-disable-next-line react/no-access-state-in-setstate
                isMonthSelection: !_this.state.isMonthSelection,
                isYearSelection: false,
            });
        };
        _this.handleYearClick = function () {
            _this.setState({
                isMonthSelection: false,
                // eslint-disable-next-line react/no-access-state-in-setstate
                isYearSelection: !_this.state.isYearSelection,
            }, _this.scrollToSelectedYear);
        };
        _this.handleSelectMonthClick = function (event) {
            var newMonth = event.target.attributes['data-month'];
            if (newMonth) {
                var monthTimestamp = parseInt(newMonth.nodeValue, 10);
                if (_this.props.onMonthChange) {
                    _this.props.onMonthChange(monthTimestamp);
                }
                else {
                    _this.setState({
                        month: monthTimestamp,
                    });
                }
                _this.setState({
                    isMonthSelection: false,
                });
                _this.root.focus();
            }
        };
        _this.handleSelectYearClick = function (event) {
            var newYear = event.target.attributes['data-year'];
            if (newYear) {
                var yearTimestamp = parseInt(newYear.nodeValue, 10);
                if (_this.props.onMonthChange) {
                    _this.props.onMonthChange(yearTimestamp);
                }
                else {
                    _this.setState({
                        month: yearTimestamp,
                    });
                }
                _this.setState({
                    isYearSelection: false,
                });
                _this.root.focus();
            }
        };
        _this.handleDayClick = function (event) {
            var day = event.target.attributes['data-day'];
            if (day) {
                _this.performChange(parseInt(day.nodeValue, 10));
            }
        };
        _this.handleFocus = function (event) {
            if (_this.blurTimeoutId) {
                clearTimeout(_this.blurTimeoutId);
                _this.blurTimeoutId = null;
            }
            if (_this.props.onFocus) {
                _this.props.onFocus(event);
            }
        };
        _this.handleBlur = function (event) {
            event.persist();
            if (_this.blurTimeoutId) {
                clearTimeout(_this.blurTimeoutId);
            }
            _this.blurTimeoutId = window.setTimeout(function () {
                if (window_1.isNodeOutsideElement(document.activeElement, _this.root) && _this.props.onBlur) {
                    _this.props.onBlur(event);
                }
                _this.blurTimeoutId = null;
            }, 0);
        };
        _this.handleArrowClick = function (event) {
            if (event.currentTarget.attributes['data-disabled'].nodeValue === 'true') {
                return;
            }
            var stepSize = event.currentTarget.attributes['data-step'].nodeValue;
            var step = parseInt(stepSize, 10);
            var newMonth = new Date(_this.state.month);
            newMonth.setMonth(newMonth.getMonth() + step);
            if (_this.props.onMonthChange) {
                _this.props.onMonthChange(newMonth.valueOf());
            }
            else {
                _this.setState({
                    month: newMonth.valueOf(),
                });
            }
        };
        _this.handleKeyDown = function (event) {
            switch (event.which) {
                case keyboard_code_1.default.DOWN_ARROW: {
                    event.preventDefault();
                    _this.performChangeWithShift(7, true);
                    break;
                }
                case keyboard_code_1.default.UP_ARROW:
                    event.preventDefault();
                    _this.performChangeWithShift(-7, true);
                    break;
                case keyboard_code_1.default.LEFT_ARROW: {
                    event.preventDefault();
                    _this.performChangeWithShift(-1, true);
                    break;
                }
                case keyboard_code_1.default.RIGHT_ARROW: {
                    event.preventDefault();
                    _this.performChangeWithShift(1, true);
                    break;
                }
            }
            if (_this.props.onKeyDown) {
                _this.props.onKeyDown(event);
            }
        };
        _this.handleKeyUp = function (event) {
            if (_this.props.onKeyUp) {
                _this.props.onKeyUp(event);
            }
        };
        return _this;
    }
    Calendar_1 = Calendar;
    // eslint-disable-next-line camelcase
    Calendar.prototype.UNSAFE_componentWillMount = function () {
        this.prepareData();
    };
    // eslint-disable-next-line camelcase
    Calendar.prototype.UNSAFE_componentWillReceiveProps = function (nextProps) {
        this.prepareData(nextProps);
    };
    Calendar.prototype.componentWillUnmount = function () {
        if (this.blurTimeoutId) {
            clearTimeout(this.blurTimeoutId);
            this.blurTimeoutId = null;
        }
    };
    Calendar.prototype.render = function () {
        var _this = this;
        return (react_1.default.createElement("div", { ref: function (root) {
                _this.root = root;
            }, className: this.cn({ width: this.props.width }), id: this.props.id, role: "grid", tabIndex: 0, onBlur: this.handleBlur, onFocus: this.handleFocus, onKeyDown: this.props.isKeyboard && this.handleKeyDown, onKeyUp: this.props.isKeyboard && this.handleKeyUp, "data-test-id": this.props['data-test-id'] },
            this.renderTitle(),
            this.renderContent()));
    };
    Calendar.prototype.renderTitle = function () {
        var month = new Date(this.state.month);
        var isPrevMonthEnabled = !this.earlierLimit
            || difference_in_months_1.default(month, start_of_month_1.default(this.earlierLimit)) > 0;
        var isNextMonthEnabled = !this.laterLimit
            || difference_in_months_1.default(month, this.laterLimit) < 0;
        var areArrowsVisible = this.props.showArrows
            && !this.state.isMonthSelection
            && !this.state.isYearSelection;
        return (react_1.default.createElement("div", { className: this.cn('title') },
            areArrowsVisible && (react_1.default.createElement("div", { className: this.cn('arrow', {
                    direction: 'left',
                    disabled: !isPrevMonthEnabled,
                }), "data-step": "-1", "data-disabled": !isPrevMonthEnabled, role: "button", tabIndex: 0, onClick: this.handleArrowClick },
                react_1.default.createElement(icons_glyph_1.ArrowBackMIcon, null))),
            areArrowsVisible && (react_1.default.createElement("div", { className: this.cn('arrow', {
                    direction: 'right',
                    disabled: !isNextMonthEnabled,
                }), "data-step": "1", "data-disabled": !isNextMonthEnabled, role: "button", tabIndex: 0, onClick: this.handleArrowClick },
                react_1.default.createElement(icons_glyph_1.ArrowForwardMIcon, null))),
            react_1.default.createElement("div", { className: this.cn('select-buttons') },
                react_1.default.createElement("div", { className: this.cn('name', {
                        month: true,
                    }), role: "button", tabIndex: 0, onClick: this.handleMonthClick },
                    react_1.default.createElement("div", { className: this.cn('select-text') }, this.props.months[month.getMonth()]),
                    react_1.default.createElement("div", { className: this.cn('select-arrows') },
                        react_1.default.createElement(icons_classic_1.ArrowSelectMIcon, null))),
                react_1.default.createElement("div", { className: this.cn('name', {
                        year: true,
                    }), role: "button", tabIndex: 0, onClick: this.handleYearClick },
                    react_1.default.createElement("div", { className: this.cn('select-text') }, "" + month.getFullYear()),
                    react_1.default.createElement("div", { className: this.cn('select-arrows') },
                        react_1.default.createElement(icons_classic_1.ArrowSelectMIcon, null))))));
    };
    Calendar.prototype.renderContent = function () {
        return (react_1.default.createElement(react_1.default.Fragment, null,
            this.state.isMonthSelection ? this.renderMonths() : null,
            this.state.isYearSelection ? this.renderYears() : null,
            this.renderDays()));
    };
    Calendar.prototype.renderMonths = function () {
        var _this = this;
        return (react_1.default.createElement("div", { className: this.cn('wrapper') },
            react_1.default.createElement("div", { className: this.cn('months') }, this.props.months.map(function (month, index) {
                var monthStart = start_of_month_1.default(set_month_1.default(_this.state.month, index));
                var monthEnd = end_of_month_1.default(monthStart);
                var allMonthDays = each_day_1.default(monthStart, monthEnd);
                var off = !allMonthDays.find(function (day) { return _this.isValidDate(day); });
                var selectedDate = new Date(_this.state.month);
                var isSameMonth = selectedDate
                    && selectedDate.getMonth() === monthStart.getMonth();
                var dataMonth = off ? null : monthStart.getTime();
                var mods = {
                    type: off ? 'off' : null,
                    state: isSameMonth ? 'current' : null,
                };
                return (react_1.default.createElement("div", { className: _this.cn('select', __assign({ month: true }, mods)), key: "month_" + (index + 1), role: "gridcell", tabIndex: 0, "data-month": dataMonth, onClick: _this.handleSelectMonthClick }, month));
            }))));
    };
    Calendar.prototype.renderYears = function () {
        var _this = this;
        return (react_1.default.createElement("div", { className: this.cn('wrapper') },
            react_1.default.createElement("div", { className: this.cn('years'), ref: this.yearsListRef }, this.years.map(function (year, index) {
                var newYear = set_year_1.default(_this.state.month, year);
                var dataYear = newYear.getTime();
                var selectedDate = new Date(_this.state.month);
                var isSameYear = selectedDate
                    && selectedDate.getFullYear() === newYear.getFullYear();
                var mods = {
                    state: isSameYear ? 'current' : null,
                };
                return (react_1.default.createElement("div", { className: _this.cn('select', __assign({ year: true }, mods)), key: "year_" + (index + 1), role: "gridcell", tabIndex: 0, "data-year": dataYear, onClick: _this.handleSelectYearClick, ref: isSameYear ? _this.selectedYearRef : undefined }, year));
            }))));
    };
    Calendar.prototype.renderDays = function () {
        var _this = this;
        var rows = __spreadArrays([
            this.renderShortWeekdays()
        ], this.renderMonth());
        return (react_1.default.createElement("table", { className: this.cn('layout') },
            react_1.default.createElement("tbody", null, rows.map(function (row, index) { return (react_1.default.createElement("tr", { className: _this.cn('row'), key: "row_" + (index + 1) }, row)); }))));
    };
    Calendar.prototype.renderShortWeekdays = function () {
        var _this = this;
        return this.props.weekdays.map(function (weekdayName, index) { return (react_1.default.createElement("th", { className: _this.cn('dayname', { type: index > 4 ? 'weekend' : false }), key: weekdayName }, weekdayName)); });
    };
    Calendar.prototype.renderMonth = function () {
        var _this = this;
        return this.calculateWeeks().map(function (week) { return _this.renderWeek(week); });
    };
    Calendar.prototype.renderWeek = function (week) {
        var _this = this;
        return week.map(function (day, index) {
            var off = !_this.isValidDate(day) || _this.isOffDay(day);
            var event = _this.isEventDay(day);
            var current = utils_1.isCurrentDay(day);
            var val = _this.value;
            var weekend = index > 4;
            var mods = {};
            if (day) {
                var isSameDate = val && val.getTime() === day.getTime();
                var isBetweenPeriod = _this.selectedFrom && _this.selectedTo
                    && _this.selectedFrom <= day && _this.selectedTo >= day;
                if (off || weekend) {
                    if (weekend) {
                        mods.type = off ? 'weekend-off' : 'weekend';
                    }
                    else {
                        mods.type = 'off';
                    }
                }
                mods.event = event;
                if (current && _this.props.showToday) {
                    mods.state = 'today';
                }
                if (isSameDate || isBetweenPeriod) {
                    mods.state = 'current';
                }
            }
            else {
                mods.empty = true;
            }
            var dataDay = day && !off
                ? day.getTime()
                : null;
            return (react_1.default.createElement("td", { key: day || "day_" + (index + 1) },
                react_1.default.createElement("div", { className: _this.cn('day', mods), role: "gridcell", tabIndex: 0, "data-day": dataDay, onClick: _this.handleDayClick },
                    day ? day.getDate() : '',
                    mods.event && (react_1.default.createElement("span", { "data-day": dataDay, className: _this.cn('event') })))));
        });
    };
    /**
     * Устанавливает фокус на календарь.
     */
    Calendar.prototype.focus = function () {
        this.root.focus();
    };
    /**
     * Убирает фокус с календаря.
     */
    // eslint-disable-next-line class-methods-use-this
    Calendar.prototype.blur = function () {
        if (document.activeElement) {
            document.activeElement.blur();
        }
    };
    /**
     * Возвращает корневой `HTMLElement` компонента.
     */
    Calendar.prototype.getNode = function () {
        return this.root;
    };
    /**
     * Пролистывает список с годами до выбранного года.
     */
    Calendar.prototype.scrollToSelectedYear = function () {
        var selectedYear = this.selectedYearRef.current;
        var yearsList = this.yearsListRef.current;
        if (selectedYear && yearsList) {
            var topIndent = yearsList.clientHeight / 2 - selectedYear.clientHeight / 2;
            yearsList.scrollTop = selectedYear.offsetTop - topIndent;
        }
    };
    /**
     * Возвращает `true`, если переданная дата является валидной и
     * попадает в заданные лимиты календаря.
     *
     * @param value Дата для проверки
     */
    Calendar.prototype.isValidDate = function (value) {
        if (!value) {
            return false;
        }
        /* eslint-disable no-restricted-globals */
        if (!(value instanceof Date) || !isFinite(value.valueOf())) {
            return false;
        }
        /* eslint-enable no-restricted-globals */
        return !((this.earlierLimit && this.earlierLimit > value)
            || (this.laterLimit && this.laterLimit < value));
    };
    /**
     * Возвращает `true`, если переданная дата является выходным днем.
     *
     * @param date Дата для проверки
     */
    Calendar.prototype.isOffDay = function (date) {
        if (this.props.offDays && Array.isArray(this.props.offDays)) {
            if (this.props.ignoreTimezone) {
                return Calendar_1.checkDaysIgnoringTimezone(this.props.offDays, date);
            }
            var timestamp = date.valueOf();
            // Поскольку offDays - отсортирован, используем бинарный поиск, O(log n) против O(n) для обычного поиска
            return lodash_sortedindexof_1.default(this.props.offDays, timestamp) !== -1;
        }
        return false;
    };
    /**
     * Возвращает `true`, если переданная дата является днем с событиями.
     *
     * @param date Дата для проверки
     */
    Calendar.prototype.isEventDay = function (date) {
        if (this.props.eventDays && Array.isArray(this.props.eventDays) && date !== null) {
            if (this.props.ignoreTimezone) {
                return Calendar_1.checkDaysIgnoringTimezone(this.props.eventDays, date);
            }
            var timestamp = date.valueOf();
            // Поскольку eventDays - отсортирован, используем бинарный поиск, O(log n) против O(n) для обычного поиска
            return lodash_sortedindexof_1.default(this.props.eventDays, timestamp) !== -1;
        }
        return false;
    };
    /**
     * Генерирует событие, что значие даты изменилось.
     *
     * @param timestamp Дата
     * @param isTriggeredByKeyboard Флаг, что событие
     * произошло из-за нажатия пользователем кнопки на клавиатуре
     */
    Calendar.prototype.performChange = function (timestamp, isTriggeredByKeyboard) {
        if (isTriggeredByKeyboard === void 0) { isTriggeredByKeyboard = false; }
        if (!this.props.onValueChange) {
            return;
        }
        var date = new Date(timestamp);
        if (!this.isValidDate(date) || this.isOffDay(date)) {
            return;
        }
        this.props.onValueChange(timestamp.valueOf(), format_1.default(date, this.props.outputFormat), isTriggeredByKeyboard);
    };
    /**
     * Генерирует событие, что значение даты изменилось на переданной число дней.
     *
     * @param dayShift Смещение текущей даты в днях.
     * @param isTriggeredByKeyboard Флаг, что событие
     * произошло из-за нажатия пользователем кнопки на клавиатуре
     */
    Calendar.prototype.performChangeWithShift = function (dayShift, isTriggeredByKeyboard) {
        if (!this.ensureValueInLimits(dayShift)) {
            return;
        }
        while (this.isOffDay(add_days_1.default(this.value, dayShift))) {
            dayShift += Math.abs(dayShift) / dayShift;
        }
        if (this.value) {
            var shiftedValue = add_days_1.default(this.value, dayShift);
            this.performChange(shiftedValue.valueOf(), isTriggeredByKeyboard);
            if (this.props.onMonthChange && !is_same_month_1.default(shiftedValue, this.value)) {
                this.props.onMonthChange(shiftedValue.valueOf());
            }
        }
        else {
            this.performChange(this.state.month, true);
        }
    };
    Calendar.prototype.ensureValueInLimits = function (dayShift) {
        var shiftedDay = add_days_1.default(this.value, dayShift);
        return (!this.earlierLimit || difference_in_milliseconds_1.default(shiftedDay, this.earlierLimit) >= 0)
            && (!this.laterLimit || difference_in_milliseconds_1.default(shiftedDay, this.laterLimit) <= 0);
    };
    Calendar.prototype.calculateWeeks = function () {
        var weekDay;
        var weekCounter = TOTAL_WEEK_NUMBER;
        var weeks = [];
        var lastDay = SUNDAY_INDEX;
        var currentMonth = new Date(this.state.month).getMonth();
        var dateIterator = new Date(this.state.month);
        // Далее я использую map для обхода массива, но при создании через new Array(DAYS_IN_WEEK);
        // map не вызывает колбек, для ключей, к которым не были приассигнены значения
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
        // соответственно пропадают undefined значения, поэтому:
        var week = (new Array(DAYS_IN_WEEK)).fill(null);
        dateIterator.setDate(1);
        while (weekCounter > 0) {
            weekDay = date_utils_1.getRussianWeekDay(dateIterator); // Получаем 0 - пн, 1 - вт, и т.д.
            if (dateIterator.getMonth() === currentMonth) {
                week[weekDay] = new Date(dateIterator.getTime());
            }
            if (weekDay === lastDay) {
                weeks.push(week);
                weekCounter -= 1;
                week = (new Array(DAYS_IN_WEEK)).fill(null);
            }
            dateIterator.setDate(dateIterator.getDate() + 1);
        }
        if (weekDay !== lastDay) {
            weeks.push(week);
        }
        return weeks;
    };
    Calendar.prototype.prepareData = function (nextProps) {
        var isInitializing = false;
        if (!nextProps) {
            nextProps = this.props;
            isInitializing = true;
        }
        if (isInitializing || this.props.value !== nextProps.value) {
            if (nextProps.value) {
                this.value = start_of_day_1.default(date_utils_1.normalizeDate(nextProps.value));
            }
            else {
                this.value = null;
            }
        }
        var month;
        if (nextProps.month) {
            month = date_utils_1.normalizeDate(nextProps.month);
        }
        else if (this.value) {
            month = new Date(this.value.valueOf());
        }
        else {
            month = new Date();
        }
        this.setState({
            month: start_of_month_1.default(month),
        });
        if (isInitializing || this.props.earlierLimit !== nextProps.earlierLimit) {
            if (nextProps.earlierLimit) {
                this.earlierLimit = date_utils_1.normalizeDate(nextProps.earlierLimit);
            }
            else {
                this.earlierLimit = sub_years_1.default(new Date(), EARLY_YEARS_LIMIT);
            }
            this.earlierLimit = start_of_day_1.default(this.earlierLimit);
            if (this.value) {
                var maxTimestamp = Math.max(this.value.valueOf(), this.earlierLimit.valueOf());
                this.value = new Date(maxTimestamp);
            }
        }
        if (isInitializing || this.props.laterLimit !== nextProps.laterLimit) {
            if (nextProps.laterLimit) {
                this.laterLimit = date_utils_1.normalizeDate(nextProps.laterLimit);
            }
            else {
                this.laterLimit = add_years_1.default(new Date(), LATER_YEARS_LIMIT);
            }
            this.laterLimit = start_of_day_1.default(this.laterLimit);
            if (this.value) {
                var minTimestamp = Math.min(this.value.valueOf(), this.laterLimit.valueOf());
                this.value = new Date(minTimestamp);
            }
        }
        this.years = utils_1.getYearsRange(this.earlierLimit, this.laterLimit);
        if (isInitializing || this.props.selectedTo !== nextProps.selectedTo) {
            this.selectedTo = nextProps.selectedTo ? date_utils_1.normalizeDate(nextProps.selectedTo) : null;
        }
        if (isInitializing || this.props.selectedFrom !== nextProps.selectedFrom) {
            this.selectedFrom = nextProps.selectedFrom
                ? date_utils_1.normalizeDate(nextProps.selectedFrom) : null;
        }
    };
    /**
     * Проверяет наличие даты в списке дат с игнорированием таймзоны.
     *
     * @param date Дата
     * @param daysToСheck Список дат для проверки
     */
    Calendar.checkDaysIgnoringTimezone = function (daysToCheck, date) {
        var dateWithoutTime = format_1.default(date, WITHOUT_TIME_FORMAT);
        /* Используем бинарный поиск */
        var index = lodash_sortedindexby_1.default(daysToCheck, dateWithoutTime, function (day) { return format_1.default(day, WITHOUT_TIME_FORMAT); });
        return dateWithoutTime === format_1.default(daysToCheck[index], WITHOUT_TIME_FORMAT);
    };
    var Calendar_1;
    Calendar.defaultProps = {
        selectedFrom: null,
        selectedTo: null,
        outputFormat: 'DD.MM.YYYY',
        weekdays: ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'],
        months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
            'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
        offDays: [],
        eventDays: [],
        showToday: false,
        showArrows: true,
        isKeyboard: true,
        ignoreTimezone: false,
    };
    Calendar = Calendar_1 = __decorate([
        performance_1.default(true)
    ], Calendar);
    return Calendar;
}(react_1.default.Component));
exports.Calendar = Calendar;
exports.default = cn_1.withTheme(Calendar);

//# sourceMappingURL=calendar.js.map
