constructor(props: Object) { super(props); const months = Moment.monthsShort(); let groups = []; let group = []; _.map(months, (month, index) => { if (index % 3 === 0) { group = []; groups.push(group); } // Check if the month is valid. let maxChoice = Moment(this.props.focus).month(index).endOf('month'); let minChoice = Moment(this.props.focus).month(index).startOf('month'); group.push({ valid: this.props.maxDate.diff(minChoice, 'seconds') >= 0 && this.props.minDate.diff(maxChoice, 'seconds') <= 0, name: month, index, }); }) this.state = { months: groups, }; }
render() { const self = this; // Get current year const year = moment().year(); // Callbacks const consumptionCallback = (attribute) => (attribute.consumption); // Get all readings from current year let currentYear = this.props.measurement.attributes.map(attribute => ({ label: attribute.name + ' ' + year, config: { color: COLOR['googleBlue500'].color }, data: measurementUtils.getReadingsOfYear(self.props.measurement.readings, attribute._id, consumptionCallback, year) })); // Get all readings from previous year let previousYear = this.props.measurement.attributes.map(attribute => ({ label: attribute.name + ' ' + (year - 1), config: { color: COLOR['googleGrey500'].color }, data: measurementUtils.getReadingsOfYear(self.props.measurement.readings, attribute._id, consumptionCallback, year - 1) })); let data = { xValues: moment.monthsShort().map(str => ( // Convert first character to upper case str.substr(0, 1).toUpperCase() + str.substr(1) )), yValues: [ ...currentYear, ...previousYear ] }; let chart = ( <BarChart ref="chart" style={{ flex: 1, width: this.state.availableWidth, height: 150 }} data={data} xAxis={{ drawGridLines: false, gridLineWidth: 1, position: "BOTTOM" }} yAxisRight={{ enable: false }} yAxisLeft={{ enable: false }} yAxis={{ startAtZero: false, drawGridLines: false }} drawGridBackground={false} backgroundColor="WHITE" description={""} zoomTo={{ scaleX: 2, xValue: 0 }} /> ); return ( <View ref="container" style={styles.container} onLayout={event => this._onLayout(this, event)}> {chart} </View> ); }
getMonth() { const month = this.props.date.month() return moment.monthsShort().map((item, i) => { return { label: item, disabled: this.checkIfMonthDisabled(i), curr: i === month } }) }
function parseMonths(curMonth, curYear) { var months = moment.monthsShort().map(function(month, i) { var year = curMonth > i ? curYear + 1 : curYear; return { index: i, date: getDaysInMonth(i, year) + '-' + month + '-' + year, name: month, }; }); // reorder months and add year return months.slice(curMonth).concat(curYear + 1).concat(months.slice(0, curMonth)); }
fetchData() { this.setState({ isLoading: true }); let url = URLBuilder.monthlySummaryURL({ month: moment.monthsShort(this.state.month), email: this.props.user.email }); fetch(url) .then(response => response.json()) .then(response => this._handleResponse(response)) .catch(error => this.setState({ isLoading: false })); }
renderFilter(cal) { /* eslint-disable max-len */ const startYear = this.props.userCurrentYear ? moment().year() : cal.year; const minYear = startYear - this.props.backRange; return ( <div className='slds-datepicker__filter slds-grid'> <div className='slds-datepicker__filter--month slds-grid slds-grid--align-spread slds-size--2-of-3'> <div className='slds-align-middle'> <Button className='slds-align-middle' type='icon-container' icon='left' size='small' alt='Previous Month' onClick={ this.onMonthChange.bind(this, -1) } /> </div> <h2 className='slds-align-middle'>{ moment.monthsShort()[cal.month] }</h2> <div className='slds-align-middle'> <Button className='slds-align-middle' type='icon-container' icon='right' size='small' alt='Next Month' onClick={ this.onMonthChange.bind(this, 1) } /> </div> </div> <div className='slds-size--1-of-3'> <Picklist className='slds-picklist--fluid slds-shrink-none' value={ cal.year } maxHeight={this.props.pickListHeight} onSelect={ this.onYearChange.bind(this) } > { new Array((this.props.backRange + this.props.futureRange)).join('_').split('_') .map((a, i) => { let year = minYear + i; return <PicklistItem key={ year } label={ year } value={ year } />; }) } </Picklist> </div> </div> ); }
renderMonths = () => { var classes, i, month, months, monthsShort; month = (moment() || this.props.selectedDate).month(); monthsShort = moment.monthsShort(); i = 0; months = []; while (i < 12) { classes = { month: true, "active": i === month && this.props.selectedDate && this.props.viewDate.year() === this.props.selectedDate.year() }; months.push(<span className={classnames(classes)} key={i} onClick={this.props.setViewMonth}>{monthsShort[i]}</span>); i++; } return months; }
render() { let start = this.state.startDate.format('YYYY-MM-DD HH:mm:ss'); let end = this.state.endDate.format('YYYY-MM-DD HH:mm:ss'); let label = start + ' - ' + end; if (start === end) { label = start; } let locale = { format: 'YYYY-MM-DD HH:mm:ss', separator: ' - ', applyLabel: 'Apply', cancelLabel: 'Cancel', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: moment.weekdaysMin(), monthNames: moment.monthsShort(), firstDay: moment.localeData().firstDayOfWeek(), }; return ( <div className="form-group"> <label className="control-label col-md-3">Date and Time</label> <div className="col-md-4"> <DatetimeRangePicker timePicker timePicker24Hour showDropdowns timePickerSeconds locale={locale} startDate={this.state.startDate} endDate={this.state.endDate} onApply={this.handleApply} > <div className="input-group"> <input type="text" className="form-control" value={label}/> <span className="input-group-btn"> <Button className="default date-range-toggle"> <i className="fa fa-calendar"/> </Button> </span> </div> </DatetimeRangePicker> </div> </div> ); }
ngModule.controller('MainCtrl', function MainCtrl(DateService, BookAPIService, WeatherAPIService, $sce) { this.DateService = DateService; this.BookAPIService = BookAPIService; const __ = require('underscore'); const moment = require('moment'); const Calendar = require('calendar').Calendar; const cal = new Calendar(1); const weekdayNames = Array.apply(null, Array(7)).map( (___, iterate) => { return moment.weekdaysShort(iterate + 1); }); this.dotw = weekdayNames; this.moty = moment.monthsShort(); this.todayName = moment().format('ddd'); this.getArray = () => { return __.flatten(cal.monthDays(this.DateService.activeYear, this.DateService.activeMonthNum)); }; this.daysArray = this.getArray(); this.nextMonth = () => { if (this.DateService.activeMonthNum < 11) { this.DateService.activeMonthNum++; this.getMonthEvents(); } }; this.prevMonth = () => { if (this.DateService.activeMonthNum > 0) { this.DateService.activeMonthNum--; this.getMonthEvents(); } }; this.getMonthEvents = () => { this.daysArray = this.getArray(); BookAPIService.getBooked(this.DateService.activeYear, this.DateService.activeMonthNum); }; this.getMonthEvents(); WeatherAPIService .getWeather() .then(response => { BookAPIService.forecast = response.data.forecast.forecastday; const icon = response.data.current.condition.icon; this.weatherIcon = $sce.trustAsResourceUrl(icon); this.weatherIconText = response.data.current.condition.text; this.weatherTemp = response.data.current.temp_c; }); });
render() { let label = this.state.startDate.format('YYYY-MM-DD'); let locale = { format: 'YYYY-MM-DD', separator: ' - ', applyLabel: 'Apply', cancelLabel: 'Cancel', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: moment.weekdaysMin(), monthNames: moment.monthsShort(), firstDay: moment.localeData().firstDayOfWeek(), }; let buttonStyle = { width: '100%' }; return ( <div className="form-group"> <label className="control-label col-md-3">Single Date Picker</label> <div className="col-md-4"> <DatetimeRangePicker singleDatePicker showDropdowns locale={locale} startDate={this.state.startDate} onEvent={this.handleEvent} > <Button className="selected-date-range-btn" style={buttonStyle}> <div className="pull-left"> <i className="fa fa-calendar"/> <span> {label} </span> </div> <div className="pull-right"> <i className="fa fa-angle-down"/> </div> </Button> </DatetimeRangePicker> </div> </div> ); }
renderFilter(cal) { /* eslint-disable max-len */ return ( <div className='slds-datepicker__filter slds-grid'> <div className='slds-datepicker__filter--month slds-grid slds-grid--align-spread slds-size--2-of-3'> <div className='slds-align-middle'> <Button className='slds-align-middle' type='icon-container' icon='left' size='small' alt='Previous Month' onClick={ this.onMonthChange.bind(this, -1) } /> </div> <h2 className='slds-align-middle'>{ moment.monthsShort()[cal.month] }</h2> <div className='slds-align-middle'> <Button className='slds-align-middle' type='icon-container' icon='right' size='small' alt='Next Month' onClick={ this.onMonthChange.bind(this, 1) } /> </div> </div> <div className='slds-size--1-of-3'> <Select value={ cal.year } onChange={ this.onYearChange.bind(this) } > { new Array(11).join('_').split('_') .map((a, i) => { const year = (cal.year + i) - 5; return <Option key={ year } label={ year } value={ year } />; }) } </Select> </div> </div> ); }
plotForYear: function($placeholder, data, config) { if (!data || data.length == 0) return null; var M = data[0].constructor; var ry = M.getRange(data); var miny = ry[0], maxy = ry[1], dy = maxy - miny; config = $.extend({bars: {}, xaxis: {}, yaxis: {}}, (config || {})); var resolution = config.resolution || 1; // months var month_names = moment.monthsShort(); var options = { series: { points: $.extend({show: true}, plotOptions.defaults.series.points), shadowSize: 0, lines: $.extend({show: true}, plotOptions.defaults.series.lines, {fill: 0.4}), }, xaxis: $.extend({}, plotOptions.defaults.xaxis, { ticks: $.map(data, function(v, i) { return [[v.id, month_names[i * resolution]]]; }), min: 0, max: data.length, }), yaxis: $.extend({}, plotOptions.defaults.yaxis, { ticks: charts.generateTicks(ry, 4, config.yaxis.tickUnit), min: miny - 0.00 * dy, max: maxy + 0.10 * dy, }), grid: plotOptions.defaults.grid, legend: {show: false}, }; return $.plot($placeholder, [{ data: $.map(data, function(v) {return (v.value) ? [[v.id, v.value]] : null}), label: M.formatLabel(), color: plotOptions.defaults.colors[0], }], options); },
}, unix: function() { return 0; }, format: function() { return ''; }, diff: function() { return 0; } }; return defTime; } else { var mt = moment( dt ); if(mt.isValid()) return mt; throw 'Invalid date format encountered.'; } } else { if( !dt ) { return moment(); } else if( dt.isValid && dt.isValid() ) return dt; throw 'Unknown date object encountered.'; } }; var months = {}, abbr = {}; moment.months().forEach(function(m,idx){months[m.toLowerCase()]=idx+1;}); moment.monthsShort().forEach(function(m,idx){abbr[m.toLowerCase()]=idx+1;}); abbr.sept = 9; module.exports = FluentDate;
setOptions: function(options, callback) { this.startDate = new Moment().startOf('day'); this.endDate = new Moment().endOf('day'); this.minDate = false; this.maxDate = false; this.dateLimit = false; this.showDropdowns = false; this.showWeekNumbers = false; this.timePicker = false; this.timePickerIncrement = 30; this.timePicker12Hour = true; this.singleDatePicker = false; this.ranges = {}; this.opens = 'right'; if (this.element.hasClass('pull-right')) { this.opens = 'left'; } this.buttonClasses = ['btn', 'btn-small btn-sm']; this.applyClass = 'btn-success'; this.cancelClass = 'btn-default'; this.format = 'MM/DD/YYYY'; this.separator = ' - '; this.locale = { applyLabel: 'Apply', cancelLabel: 'Cancel', fromLabel: 'From', toLabel: 'To', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: Moment.weekdaysMin(), monthNames: Moment.monthsShort(), firstDay: Moment.localeData()._week.dow }; this.cb = function() { }; if (typeof options.format === 'string') { this.format = options.format; } if (typeof options.separator === 'string') { this.separator = options.separator; } if (typeof options.startDate === 'string') { this.startDate = moment(options.startDate, this.format); } if (typeof options.endDate === 'string') { this.endDate = new Moment(options.endDate, this.format); } if (typeof options.minDate === 'string') { this.minDate = new Moment(options.minDate, this.format); } if (typeof options.maxDate === 'string') { this.maxDate = new Moment(options.maxDate, this.format); } if (typeof options.startDate === 'object') { this.startDate = new Moment(options.startDate); } if (typeof options.endDate === 'object') { this.endDate = new Moment(options.endDate); } if (typeof options.minDate === 'object') { this.minDate = new Moment(options.minDate); } if (typeof options.maxDate === 'object') { this.maxDate = new Moment(options.maxDate); } if (typeof options.applyClass === 'string') { this.applyClass = options.applyClass; } if (typeof options.cancelClass === 'string') { this.cancelClass = options.cancelClass; } if (typeof options.dateLimit === 'object') { this.dateLimit = options.dateLimit; } if (typeof options.locale === 'object') { if (typeof options.locale.daysOfWeek === 'object') { // Create a copy of daysOfWeek to avoid modification of original // options object for reusability in multiple daterangepicker instances this.locale.daysOfWeek = options.locale.daysOfWeek.slice(); } if (typeof options.locale.monthNames === 'object') { this.locale.monthNames = options.locale.monthNames.slice(); } if (typeof options.locale.firstDay === 'number') { this.locale.firstDay = options.locale.firstDay; } if (typeof options.locale.applyLabel === 'string') { this.locale.applyLabel = options.locale.applyLabel; } if (typeof options.locale.cancelLabel === 'string') { this.locale.cancelLabel = options.locale.cancelLabel; } if (typeof options.locale.fromLabel === 'string') { this.locale.fromLabel = options.locale.fromLabel; } if (typeof options.locale.toLabel === 'string') { this.locale.toLabel = options.locale.toLabel; } if (typeof options.locale.weekLabel === 'string') { this.locale.weekLabel = options.locale.weekLabel; } if (typeof options.locale.customRangeLabel === 'string') { this.locale.customRangeLabel = options.locale.customRangeLabel; } } if (typeof options.opens === 'string') { this.opens = options.opens; } if (typeof options.showWeekNumbers === 'boolean') { this.showWeekNumbers = options.showWeekNumbers; } if (typeof options.buttonClasses === 'string') { this.buttonClasses = [options.buttonClasses]; } if (typeof options.buttonClasses === 'object') { this.buttonClasses = options.buttonClasses; } if (typeof options.showDropdowns === 'boolean') { this.showDropdowns = options.showDropdowns; } if (typeof options.singleDatePicker === 'boolean') { this.singleDatePicker = options.singleDatePicker; } if (typeof options.timePicker === 'boolean') { this.timePicker = options.timePicker; } if (typeof options.timePickerIncrement === 'number') { this.timePickerIncrement = options.timePickerIncrement; } if (typeof options.timePicker12Hour === 'boolean') { this.timePicker12Hour = options.timePicker12Hour; } // update day names order to firstDay if (this.locale.firstDay !== 0) { let iterator = this.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } // if no start/end dates set, check if an input element contains initial values if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') { if ($(this.element).is('input[type=text]')) { let val = $(this.element).val(); let split = val.split(this.separator); start = end = null; if (split.length === 2) { start = moment(split[0], this.format); end = moment(split[1], this.format); } else { if (this.singleDatePicker) { start = moment(val, this.format); end = moment(val, this.format); } } if (start !== null && end !== null) { this.startDate = start; this.endDate = end; } } } if (typeof options.ranges === 'object') { options.ranges.forEach((range) => { let startRange = moment(range[0]); let endRange = moment(range[1]); // If we have a min/max date set, bound this range // to it, but only if it would otherwise fall // outside of the min/max. if (this.minDate && startRange.isBefore(this.minDate)) { startRange = moment(this.minDate); } if (this.maxDate && endRange.isAfter(this.maxDate)) { endRange = moment(this.maxDate); } // If the end of the range is before the minimum (if min is set) OR // the start of the range is after the max (also if set) don't display this // range option. if (!((this.minDate && endRange.isBefore(this.minDate)) || (this.maxDate && startRange.isAfter(this.maxDate)))) { this.ranges[range] = [startRange, endRange]; } }); let list = '<ul>'; this.ranges.forEach((range) => list += '<li>' + range + '</li>'); list += '<li>' + this.locale.customRangeLabel + '</li>'; list += '</ul>'; this.container.find('.ranges ul').remove(); this.container.find('.ranges').prepend(list); } if (typeof callback === 'function') { this.cb = callback; } if (!this.timePicker) { this.startDate = this.startDate.startOf('day'); this.endDate = this.endDate.endOf('day'); } if (this.singleDatePicker) { this.opens = 'right'; this.container.find('.calendar.right').show(); this.container.find('.calendar.left').hide(); this.container.find('.ranges').hide(); if (!this.container.find('.calendar.right').hasClass('single')) { this.container.find('.calendar.right').addClass('single'); } } else { this.container.find('.calendar.right').removeClass('single'); this.container.find('.ranges').show(); } this.oldStartDate = this.startDate.clone(); this.oldEndDate = this.endDate.clone(); this.oldChosenLabel = this.chosenLabel; this.leftCalendar = { month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute()]), calendar: [] }; this.rightCalendar = { month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute()]), calendar: [] }; if (this.opens === 'right') { // swap calendar positions let left = this.container.find('.calendar.left'); let right = this.container.find('.calendar.right'); if (right.hasClass('single')) { right.removeClass('single'); left.addClass('single'); } left.removeClass('left').addClass('right'); right.removeClass('right').addClass('left'); if (this.singleDatePicker) { left.show(); right.hide(); } } if (typeof options.ranges === 'undefined' && !this.singleDatePicker) { this.container.addClass('show-calendar'); } this.container.addClass('opens' + this.opens); this.updateView(); this.updateCalendars(); },
separator: ' - ', singleDatePicker: false, placeholder: null, buttonClasses: ['btn'], applyClass: null, cancelClass: null, ranges: { 'Today': [moment(), moment()], 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Last 7 Days': [moment().subtract(6, 'days'), moment()], 'Last 30 Days': [moment().subtract(29, 'days'), moment()], 'This Month': [moment().startOf('month'), moment().endOf('month')], 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] }, daysOfWeek: moment.weekdaysMin(), monthNames: moment.monthsShort(), removeDropdownOnDestroy: false, cancelLabel: 'Cancel', applyLabel: 'Apply', customRangeLabel: 'Custom Range', fromLabel: 'From', toLabel: 'To', hideAction: null, applyAction: null, cancelAction: null, autoUpdateInput: true, autoApply: false, alwaysShowCalendars: false, firstDay: 0, // Init the dropdown when the component is added to the DOM
/** * @copyright 2014 Quri, Loïc CHOLLIER * @copyright 2015-present Prometheus Research, LLC */ import chunk from 'lodash/chunk'; import moment from 'moment'; import React from 'react'; import {Paginator} from '../ui'; import Month from './Month'; const MONTHS_SHORT = moment.monthsShort(); const YEAR_MONTH_RANGE = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; export default class MonthView extends React.Component { static propTypes = { value: React.PropTypes.object, showYears: React.PropTypes.func.isRequired, viewDate: React.PropTypes.object.isRequired, onViewDate: React.PropTypes.func.isRequired, onViewDateSelect: React.PropTypes.func.isRequired, Month: React.PropTypes.func, }; static defaultProps = { Month: Month, }; render() {