UNPKG

@atlaskit/calendar

Version:

An interactive calendar for date selection experiences.

80 lines (78 loc) 3.02 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getBaseCalendar; var _constants = require("../constants"); var _getDaysInMonth = _interopRequireDefault(require("./get-days-in-month")); /** * Logic taken from https://github.com/WesSouza/calendar-base which is not maintained for quite sometime. * This will help us fixing any issue we might get or any new functionality we might want to support. * Not changing much code below. Just removed those parts which we don't need. */ function getBaseCalendar(year, month) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { weekStartDay: 0 }, _ref$weekStartDay = _ref.weekStartDay, weekStartDay = _ref$weekStartDay === void 0 ? 0 : _ref$weekStartDay; var date = new Date(Date.UTC(year, month, 1, 0, 0, 0, 0)); var utcYear = date.getUTCFullYear(); var utcMonth = date.getUTCMonth(); var calendar = []; var firstDay = date.getUTCDay(); var firstDate = -((_constants.daysPerWeek - weekStartDay + firstDay) % _constants.daysPerWeek); var lastDate = (0, _getDaysInMonth.default)(utcYear, utcMonth); var lastDay = (lastDate - firstDate) % _constants.daysPerWeek; var lastDateOfPreviousMonth = (0, _getDaysInMonth.default)(utcYear, utcMonth - 1); var dateCounter = firstDate; var currentDay; var currentDate; var currentDateObject = null; var calculatedMonth; var calculatedYear; var maxDateCount = lastDate - dateCounter + (lastDay !== 0 ? _constants.daysPerWeek - lastDay : 0) + firstDate; while (dateCounter < maxDateCount) { currentDate = dateCounter + 1; currentDay = ((dateCounter < 1 ? _constants.daysPerWeek + dateCounter : dateCounter) + firstDay) % _constants.daysPerWeek; if (currentDate < 1 || currentDate > lastDate) { if (currentDate < 1) { calculatedMonth = utcMonth - 1; calculatedYear = utcYear; if (calculatedMonth < 0) { calculatedMonth = _constants.monthsPerYear - 1; calculatedYear--; } currentDate = lastDateOfPreviousMonth + currentDate; } else if (currentDate > lastDate) { calculatedMonth = utcMonth + 1; calculatedYear = utcYear; if (calculatedMonth > _constants.monthsPerYear - 1) { calculatedMonth = 0; calculatedYear++; } currentDate = dateCounter - lastDate + 1; } if (calculatedMonth !== undefined && calculatedYear !== undefined) { currentDateObject = { day: currentDate, weekDay: currentDay, month: calculatedMonth, year: calculatedYear, siblingMonth: true }; } } else { currentDateObject = { day: currentDate, weekDay: currentDay, month: utcMonth, year: utcYear }; } calendar.push(currentDateObject); dateCounter++; } return calendar; }