salix/front/core/components/calendar/index.js

96 lines
2.5 KiB
JavaScript

import ngModule from '../../module';
import Component from '../../lib/component';
import './style.scss';
/**
* Calendar.
*
*/
export default class Calendar extends Component {
constructor($element, $scope) {
super($element, $scope);
this.defaultDate = new Date();
}
get defaultDate() {
return this._defaultDate;
}
set defaultDate(value) {
this._defaultDate = value;
this.buildDays();
}
get lastDay() {
let year = this.defaultDate.getYear();
// Month starts from zero, so we increment one month
let month = this.defaultDate.getMonth() + 1;
return new Date(year, month, 0).getDate();
}
buildDays() {
let firstMonthDay = new Date(this.defaultDate);
firstMonthDay.setDate(1);
let weekday = firstMonthDay.getDay();
let year = this.defaultDate.getYear();
let month = this.defaultDate.getMonth();
let previousLastMonthDay = new Date(year, month, 0);
this.days = [];
let day = 1;
let previousMonthDay = previousLastMonthDay.getDate() - (weekday - 2);
let nextMonthDay = 1;
for (let d = 1; d <= 35; d++) {
if (d < weekday) {
let monthDay = new Date(previousLastMonthDay);
monthDay.setDate(previousMonthDay);
this.days.push({number: previousMonthDay, date: monthDay, color: 'gray'});
previousMonthDay++;
} else if (d >= weekday && day <= this.lastDay) {
let monthDay = new Date(this.defaultDate);
monthDay.setDate(day);
this.days.push({number: day, date: monthDay});
day++;
} else if (d >= weekday && day > this.lastDay) {
this.days.push({number: nextMonthDay, color: 'gray'});
nextMonthDay++;
}
}
}
moveNext() {
let next = this.defaultDate.getMonth() + 1;
this.defaultDate.setMonth(next);
this.buildDays();
}
movePrevious() {
let previous = this.defaultDate.getMonth() - 1;
this.defaultDate.setMonth(previous);
this.buildDays();
}
select(index) {
this.emit('selection', {value: this.days[index]});
}
}
Calendar.$inject = ['$element', '$scope', '$attrs'];
ngModule.component('vnCalendar', {
template: require('./index.html'),
controller: Calendar,
bindings: {
model: '<',
defaultDate: '<?',
onSelection: '&?'
}
});