date-fns#startOfMonth JavaScript Examples

The following examples show how to use date-fns#startOfMonth. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CalendarNavigation.js    From react-nice-dates with MIT License 6 votes vote down vote up
export default function CalendarNavigation({ locale, month, minimumDate, maximumDate, onMonthChange }) {
  const handlePrevious = event => {
    onMonthChange(startOfMonth(subMonths(month, 1)))
    event.preventDefault()
  }

  const handleNext = event => {
    onMonthChange(startOfMonth(addMonths(month, 1)))
    event.preventDefault()
  }

  return (
    <div className='nice-dates-navigation'>
      <a
        className={classNames('nice-dates-navigation_previous', {
          '-disabled': isSameMonth(month, minimumDate)
        })}
        onClick={handlePrevious}
        onTouchEnd={handlePrevious}
      />

      <span className='nice-dates-navigation_current'>
        {format(month, getYear(month) === getYear(new Date()) ? 'LLLL' : 'LLLL yyyy', { locale })}
      </span>

      <a
        className={classNames('nice-dates-navigation_next', {
          '-disabled': isSameMonth(month, maximumDate)
        })}
        onClick={handleNext}
        onTouchEnd={handleNext}
      />
    </div>
  )
}
Example #2
Source File: DatePickerCalendar.js    From react-nice-dates with MIT License 6 votes vote down vote up
export default function DatePickerCalendar({
  locale,
  date: selectedDate,
  month: receivedMonth,
  onDateChange,
  onMonthChange,
  minimumDate,
  maximumDate,
  modifiers: receivedModifiers,
  modifiersClassNames,
  weekdayFormat,
  touchDragEnabled
}) {
  const isSelected = date => isSameDay(date, selectedDate) && isSelectable(date, { minimumDate, maximumDate })
  const modifiers = mergeModifiers({ selected: isSelected, disabled: isSelected }, receivedModifiers)
  const [month, setMonth] = useControllableState(receivedMonth, onMonthChange, startOfMonth(selectedDate || new Date()))

  const handleDateChange = date => {
    onDateChange(selectedDate ? setTime(date, selectedDate) : date)
  }

  return (
    <Calendar
      locale={locale}
      month={month}
      onMonthChange={setMonth}
      onDayClick={handleDateChange}
      minimumDate={minimumDate}
      maximumDate={maximumDate}
      modifiers={modifiers}
      modifiersClassNames={modifiersClassNames}
      weekdayFormat={weekdayFormat}
      touchDragEnabled={touchDragEnabled}
    />
  )
}
Example #3
Source File: Calendar.js    From umami with MIT License 6 votes vote down vote up
MonthSelector = ({ date, minDate, maxDate, locale, onSelect }) => {
  const start = startOfYear(date);
  const months = [];
  for (let i = 0; i < 12; i++) {
    months.push(addMonths(start, i));
  }

  function handleSelect(value) {
    onSelect(setMonth(date, value));
  }

  return (
    <table>
      <tbody>
        {chunk(months, 3).map((row, i) => (
          <tr key={i}>
            {row.map((month, j) => {
              const disabled =
                isBefore(endOfMonth(month), minDate) || isAfter(startOfMonth(month), maxDate);
              return (
                <td
                  key={j}
                  className={classNames(locale, {
                    [styles.selected]: month.getMonth() === date.getMonth(),
                    [styles.disabled]: disabled,
                  })}
                  onClick={!disabled ? () => handleSelect(month.getMonth()) : null}
                >
                  {dateFormat(month, 'MMMM', locale)}
                </td>
              );
            })}
          </tr>
        ))}
      </tbody>
    </table>
  );
}
Example #4
Source File: Calendar.js    From react-nice-dates with MIT License 5 votes vote down vote up
export default function Calendar({
  locale,
  month: receivedMonth,
  modifiers: receivedModifiers,
  modifiersClassNames,
  minimumDate,
  maximumDate,
  onMonthChange,
  onDayHover,
  onDayClick,
  weekdayFormat,
  touchDragEnabled
}) {
  const [month, setMonth] = useControllableState(receivedMonth, onMonthChange, startOfMonth(new Date()))

  const modifiers = mergeModifiers(
    { disabled: date => !isSelectable(date, { minimumDate, maximumDate }) },
    receivedModifiers
  )

  return (
    <div>
      <CalendarNavigation
        locale={locale}
        minimumDate={minimumDate}
        maximumDate={maximumDate}
        month={month}
        onMonthChange={setMonth}
      />

      <CalendarWeekHeader locale={locale} weekdayFormat={weekdayFormat}/>

      <CalendarGrid
        locale={locale}
        modifiers={modifiers}
        modifiersClassNames={modifiersClassNames}
        month={month}
        onMonthChange={setMonth}
        onDayHover={onDayHover}
        onDayClick={onDayClick}
        touchDragEnabled={touchDragEnabled}
      />
    </div>
  )
}
Example #5
Source File: date.js    From umami with MIT License 5 votes vote down vote up
dateFuncs = {
  minute: [differenceInMinutes, addMinutes, startOfMinute],
  hour: [differenceInHours, addHours, startOfHour],
  day: [differenceInCalendarDays, addDays, startOfDay],
  month: [differenceInCalendarMonths, addMonths, startOfMonth],
  year: [differenceInCalendarYears, addYears, startOfYear],
}
Example #6
Source File: date.js    From umami with MIT License 5 votes vote down vote up
export function getDateRange(value, locale = 'en-US') {
  const now = new Date();
  const dateLocale = getDateLocale(locale);

  const match = value.match(/^(?<num>[0-9]+)(?<unit>hour|day|week|month|year)$/);

  if (!match) return;

  const { num, unit } = match.groups;

  if (+num === 1) {
    switch (unit) {
      case 'day':
        return {
          startDate: startOfDay(now),
          endDate: endOfDay(now),
          unit: 'hour',
          value,
        };
      case 'week':
        return {
          startDate: startOfWeek(now, { locale: dateLocale }),
          endDate: endOfWeek(now, { locale: dateLocale }),
          unit: 'day',
          value,
        };
      case 'month':
        return {
          startDate: startOfMonth(now),
          endDate: endOfMonth(now),
          unit: 'day',
          value,
        };
      case 'year':
        return {
          startDate: startOfYear(now),
          endDate: endOfYear(now),
          unit: 'month',
          value,
        };
    }
  }

  switch (unit) {
    case 'day':
      return {
        startDate: subDays(startOfDay(now), num - 1),
        endDate: endOfDay(now),
        unit,
        value,
      };
    case 'hour':
      return {
        startDate: subHours(startOfHour(now), num - 1),
        endDate: endOfHour(now),
        unit,
        value,
      };
  }
}
Example #7
Source File: crypto.js    From umami with MIT License 5 votes vote down vote up
ROTATING_SALT = hash(startOfMonth(new Date()).toUTCString())
Example #8
Source File: Calendar.js    From umami with MIT License 5 votes vote down vote up
DaySelector = ({ date, minDate, maxDate, locale, onSelect }) => {
  const dateLocale = getDateLocale(locale);
  const weekStartsOn = dateLocale?.options?.weekStartsOn || 0;
  const startWeek = startOfWeek(date, {
    locale: dateLocale,
    weekStartsOn,
  });
  const startMonth = startOfMonth(date);
  const startDay = subDays(startMonth, startMonth.getDay() - weekStartsOn);
  const month = date.getMonth();
  const year = date.getFullYear();

  const daysOfWeek = [];
  for (let i = 0; i < 7; i++) {
    daysOfWeek.push(addDays(startWeek, i));
  }

  const days = [];
  for (let i = 0; i < 35; i++) {
    days.push(addDays(startDay, i));
  }

  return (
    <table>
      <thead>
        <tr>
          {daysOfWeek.map((day, i) => (
            <th key={i} className={locale}>
              {dateFormat(day, 'EEE', locale)}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {chunk(days, 7).map((week, i) => (
          <tr key={i}>
            {week.map((day, j) => {
              const disabled = isBefore(day, minDate) || isAfter(day, maxDate);
              return (
                <td
                  key={j}
                  className={classNames({
                    [styles.selected]: isSameDay(date, day),
                    [styles.faded]: day.getMonth() !== month || day.getFullYear() !== year,
                    [styles.disabled]: disabled,
                  })}
                  onClick={!disabled ? () => onSelect(day) : null}
                >
                  {day.getDate()}
                </td>
              );
            })}
          </tr>
        ))}
      </tbody>
    </table>
  );
}
Example #9
Source File: MonthView.js    From react-horizontal-datepicker with MIT License 5 votes vote down vote up
MonthView = ({startDate, lastDate, selectDate, getSelectedDay, primaryColor, labelFormat}) => {
    const [selectedDate, setSelectedDate] = useState(null);
    const rgb = primaryColor.replace(/[^\d,]/g, '').split(',');
    const brightness = Math.round(((parseInt(rgb[0]) * 299) +
                      (parseInt(rgb[1]) * 587) +
                      (parseInt(rgb[2]) * 114)) / 1000);
    const textColour = (brightness > 125) ? 'black' : 'white';

    const selectedStyle = {borderRadius:"0.7rem",background:`${primaryColor}`, color: textColour};
    
    const getStyles = (day) => {
        return isSameDay(day, selectedDate)?selectedStyle:null;
    };
    
    const getId = (day) => {
        return isSameDay(day, selectedDate)?'selected':"";
    };

    const renderDays = () => {

        const months = [];
        
        for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
            const month = startOfMonth(addMonths(startDate, i));
            months.push(
                <div id={`${getId(month)}`}
                     className={styles.monthContainer} 
                     key={month}
                     style={getStyles(month)}
                     onClick={() => onDateClick(month)}
                >
                    <span className={styles.monthYearLabel}>
                        {format(month, labelFormat || "MMMM yyyy")}
                    </span>
                </div>
            );
        }
        
        return <div id={"container"} className={styles.dateListScrollable}>{months}</div>;
    }

    const onDateClick = day => {
        setSelectedDate(day);
        if (getSelectedDay) {
            getSelectedDay(day);
        }
    };

    useEffect(() => {
        if (getSelectedDay) {
            if (selectDate) {
                getSelectedDay(selectDate);
            } else {
                getSelectedDay(startDate);
            }
        }
    }, []);

    useEffect(() => {
        if (selectDate) {
            if (!isSameDay(selectedDate, selectDate)) {
                setSelectedDate(selectDate);
                setTimeout(() => {
                    let view = document.getElementById('selected');
                    if (view) {
                        view.scrollIntoView({behavior: "smooth", inline: "center", block: "nearest"});
                    }
                }, 20);
            }
        }
    }, [selectDate]);

    return <React.Fragment>{renderDays()}</React.Fragment>
}
Example #10
Source File: DatePickerCalendar.test.js    From react-nice-dates with MIT License 5 votes vote down vote up
describe('DatePickerCalendar', () => {
  it('should render', () => {
    const { getAllByText } = render(<DatePickerCalendar locale={locale} />)

    expect(getAllByText('1').length).toBeGreaterThan(0)
  })

  it('should call onDateChange on date selection', () => {
    const handleDateChange = jest.fn()

    const { getAllByText } = render(<DatePickerCalendar locale={locale} onDateChange={handleDateChange} />)

    fireEvent.click(getAllByText('1')[0])

    expect(handleDateChange).toHaveBeenCalledTimes(1)
  })

  it('should display selected date', () => {
    const { getAllByText } = render(<DatePickerCalendar locale={locale} date={startOfMonth(new Date())} />)

    expect(getAllByText('1')[0].parentElement).toHaveClass('-selected')
  })

  it('should display pre-selected date’s month on initial render', () => {
    const pastDate = subMonths(new Date(), 1)
    const monthName = format(pastDate, 'LLLL', { locale })

    const { getByText } = render(<DatePickerCalendar locale={locale} date={pastDate} />)

    expect(getByText(monthName, { exact: false })).toBeInTheDocument()
  })

  it('should maintain the selected date’s time when selecting a new date', () => {
    const handleDateChange = jest.fn()
    const date = new Date(2020, 1, 24, 18, 30)

    const { getByText } = render(<DatePickerCalendar locale={locale} date={date} onDateChange={handleDateChange} />)

    fireEvent.click(getByText('25'))

    expect(handleDateChange).toHaveBeenCalledWith(new Date(2020, 1, 25, 18, 30))
  })
})
Example #11
Source File: useGrid.js    From react-nice-dates with MIT License 5 votes vote down vote up
getStartDate = (date, locale) => startOfWeek(startOfMonth(date), { locale })
Example #12
Source File: useGrid.js    From react-nice-dates with MIT License 5 votes vote down vote up
rowsInMonth = (date, locale) => rowsBetweenDates(startOfMonth(date), endOfMonth(date), locale)
Example #13
Source File: CalendarGrid.js    From react-nice-dates with MIT License 5 votes vote down vote up
export default function CalendarGrid({
  locale,
  month,
  modifiers,
  modifiersClassNames,
  onMonthChange,
  onDayHover,
  onDayClick,
  transitionDuration,
  touchDragEnabled
}) {
  const grid = useGrid({ locale, month: startOfMonth(month), onMonthChange, transitionDuration, touchDragEnabled })
  const { startDate, endDate, cellHeight, containerElementRef, isWide, offset, origin, transition } = grid

  const days = eachDayOfInterval({
    start: startDate,
    end: endDate
  }).map(date => {
    return (
      <CalendarDay
        date={date}
        height={cellHeight}
        key={lightFormat(date, 'yyyy-MM-dd')}
        locale={locale}
        modifiers={{
          ...computeModifiers(modifiers, date),
          outside: !isSameMonth(date, month),
          wide: isWide
        }}
        modifiersClassNames={modifiersClassNames}
        onHover={onDayHover}
        onClick={onDayClick}
      />
    )
  })

  return (
    <div className='nice-dates-grid' style={{ height: cellHeight * 6 }}>
      <div
        className={classNames('nice-dates-grid_container', {
          '-moving': offset,
          '-origin-bottom': origin === ORIGIN_BOTTOM,
          '-origin-top': origin === ORIGIN_TOP,
          '-transition': transition
        })}
        ref={containerElementRef}
        style={{
          transform: `translate3d(0, ${offset}px, 0)`,
          transitionDuration: `${transitionDuration}ms`
        }}
      >
        {days}
      </div>
    </div>
  )
}
Example #14
Source File: DateRangePickerCalendar.test.js    From react-nice-dates with MIT License 4 votes vote down vote up
describe('DateRangePickerCalendar', () => {
  it('should render', () => {
    const { getAllByText } = render(
      <DateRangePickerCalendar
        locale={locale}
        onStartDateChange={() => {}}
        onEndDateChange={() => {}}
        onFocusChange={() => {}}
      />
    )

    expect(getAllByText('1').length).toBeGreaterThan(0)
  })

  it('should call callbacks on date selection', () => {
    const handleStartDateChange = jest.fn()
    const handleEndDateChange = jest.fn()
    const handleFocusChange = jest.fn()

    const { getAllByText, rerender } = render(
      <DateRangePickerCalendar
        locale={locale}
        focus={START_DATE}
        onStartDateChange={handleStartDateChange}
        onEndDateChange={handleEndDateChange}
        onFocusChange={handleFocusChange}
      />
    )

    fireEvent.click(getAllByText('1')[0])

    expect(handleStartDateChange).toHaveBeenCalledTimes(1)
    expect(handleEndDateChange).toHaveBeenCalledTimes(0)
    expect(handleFocusChange).toHaveBeenCalledWith(END_DATE)

    rerender(
      <DateRangePickerCalendar
        locale={locale}
        focus={END_DATE}
        startDate={startOfMonth(new Date())}
        onStartDateChange={handleStartDateChange}
        onEndDateChange={handleEndDateChange}
        onFocusChange={handleFocusChange}
      />
    )

    fireEvent.click(getAllByText('2')[0])

    expect(handleStartDateChange).toHaveBeenCalledTimes(1)
    expect(handleEndDateChange).toHaveBeenCalledTimes(1)
    expect(handleFocusChange).toHaveBeenCalledWith(null)
  })

  it('should display selected date range', () => {
    const startDate = startOfMonth(new Date())
    const endDate = addDays(startDate, 2)

    const { container, getAllByText, rerender } = render(
      <DateRangePickerCalendar locale={locale} startDate={startDate} />
    )

    expect(getAllByText('1')[0].parentElement).toHaveClass('-selected')
    expect(container.querySelectorAll('.-selected').length).toBe(1)

    rerender(<DateRangePickerCalendar locale={locale} startDate={startDate} endDate={endDate} />)

    expect(getAllByText('1')[0].parentElement).toHaveClass('-selected -selected-start')
    expect(getAllByText('2')[0].parentElement).toHaveClass('-selected -selected-middle')
    expect(getAllByText('3')[0].parentElement).toHaveClass('-selected -selected-end')
    expect(container.querySelectorAll('.-selected').length).toBe(3)
  })

  it('should display pre-selected start date’s month on initial render', () => {
    const today = new Date()
    const pastDate = subMonths(today, 1)
    const monthName = format(pastDate, 'LLLL', { locale })

    const { getByText } = render(<DateRangePickerCalendar locale={locale} startDate={pastDate} endDate={today} />)

    expect(getByText(monthName, { exact: false })).toBeInTheDocument()
  })

  it('should display pre-selected end date’s month on initial render', () => {
    const pastDate = subMonths(new Date(), 1)
    const monthName = format(pastDate, 'LLLL', { locale })

    const { getByText } = render(<DateRangePickerCalendar locale={locale} endDate={pastDate} />)

    expect(getByText(monthName, { exact: false })).toBeInTheDocument()
  })

  it('should maintain the selected start date’s time when selecting a new date', () => {
    const handleStartDateChange = jest.fn()

    const { getByText } = render(
      <DateRangePickerCalendar
        locale={locale}
        focus={START_DATE}
        startDate={new Date(2020, 1, 24, 18, 30)}
        onStartDateChange={handleStartDateChange}
      />
    )

    fireEvent.click(getByText('25'))

    expect(handleStartDateChange).toHaveBeenCalledWith(new Date(2020, 1, 25, 18, 30))
  })

  it('should maintain the selected end date’s time when selecting a new date', () => {
    const handleEndDateChange = jest.fn()

    const { getByText } = render(
      <DateRangePickerCalendar
        locale={locale}
        focus={END_DATE}
        endDate={new Date(2020, 1, 24, 18, 30)}
        onEndDateChange={handleEndDateChange}
      />
    )

    fireEvent.click(getByText('25'))

    expect(handleEndDateChange).toHaveBeenCalledWith(new Date(2020, 1, 25, 18, 30))
  })

  it('should allow same day selection by default (when minimumLength is 0)', () => {
    const startDate = startOfDay(set(new Date(), { date: 13 }))

    const { getByText } = render(<DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} />)

    expect(getByText('13').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable dates before the start date when selecting an end date with no existing end date selected', () => {
    const startDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(<DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} />)

    expect(getByText('16').parentElement).toHaveClass('-disabled')
    expect(getByText('17').parentElement).toHaveClass('-disabled')
    expect(getByText('18').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable dates after the end date when selecting a start date with no existing start date selected', () => {
    const endDate = startOfDay(set(new Date(), { date: 13 }))

    const { getByText } = render(<DateRangePickerCalendar locale={locale} focus={START_DATE} endDate={endDate} />)

    expect(getByText('13').parentElement).not.toHaveClass('-disabled')
    expect(getByText('14').parentElement).toHaveClass('-disabled')
    expect(getByText('15').parentElement).toHaveClass('-disabled')
  })

  it('should disable in-between dates when minimumLength is set', () => {
    const startDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} minimumLength={3} />
    )

    expect(getByText('18').parentElement).toHaveClass('-disabled')
    expect(getByText('19').parentElement).toHaveClass('-disabled')
    expect(getByText('20').parentElement).toHaveClass('-disabled')
    expect(getByText('21').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable in-between dates when selecting start date and minimumLength is set', () => {
    const endDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={START_DATE} endDate={endDate} minimumLength={3} />
    )

    expect(getByText('18').parentElement).toHaveClass('-disabled')
    expect(getByText('17').parentElement).toHaveClass('-disabled')
    expect(getByText('16').parentElement).toHaveClass('-disabled')
    expect(getByText('15').parentElement).not.toHaveClass('-disabled')
  })

  it('should disable later dates when maximumLength is set', () => {
    const startDate = startOfDay(set(new Date(), { date: 13 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={END_DATE} startDate={startDate} maximumLength={3} />
    )

    expect(getByText('13').parentElement).not.toHaveClass('-disabled')
    expect(getByText('14').parentElement).not.toHaveClass('-disabled')
    expect(getByText('15').parentElement).not.toHaveClass('-disabled')
    expect(getByText('16').parentElement).not.toHaveClass('-disabled')
    expect(getByText('17').parentElement).toHaveClass('-disabled')
  })

  it('should disable earlier dates when selecting start date and maximumLength is set', () => {
    const endDate = startOfDay(set(new Date(), { date: 18 }))

    const { getByText } = render(
      <DateRangePickerCalendar locale={locale} focus={START_DATE} endDate={endDate} maximumLength={3} />
    )

    expect(getByText('18').parentElement).not.toHaveClass('-disabled')
    expect(getByText('17').parentElement).not.toHaveClass('-disabled')
    expect(getByText('16').parentElement).not.toHaveClass('-disabled')
    expect(getByText('15').parentElement).not.toHaveClass('-disabled')
    expect(getByText('14').parentElement).toHaveClass('-disabled')
  })
})
Example #15
Source File: DateView.js    From react-horizontal-datepicker with MIT License 4 votes vote down vote up
DateView = ({
  startDate,
  lastDate,
  selectDate,
  getSelectedDay,
  primaryColor,
  labelFormat
}) => {
  const [selectedDate, setSelectedDate] = useState(null);
  const firstSection = {
    marginLeft: '40px'
  };
  const selectedStyle = {
    fontWeight: "bold",
    width: "45px",
    height: "45px",
    borderRadius: "50%",
    border: `2px solid ${primaryColor}`,
    color: primaryColor
  };
  const labelColor = {
    color: primaryColor
  };

  const getStyles = day => {
    return isSameDay(day, selectedDate) ? selectedStyle : null;
  };

  const getId = day => {
    return isSameDay(day, selectedDate) ? 'selected' : "";
  };

  const renderDays = () => {
    const dayFormat = "E";
    const dateFormat = "d";
    const months = [];
    let days = [];

    for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
      let start, end;
      const month = startOfMonth(addMonths(startDate, i));
      start = i === 0 ? Number(format(startDate, dateFormat)) - 1 : 0;
      end = i === differenceInMonths(lastDate, startDate) ? Number(format(lastDate, "d")) : Number(format(lastDayOfMonth(month), "d"));

      for (let j = start; j < end; j++) {
        let currentDay = addDays(month, j);
        days.push( /*#__PURE__*/React.createElement("div", {
          id: `${getId(currentDay)}`,
          className: styles.dateDayItem,
          style: getStyles(currentDay),
          key: currentDay,
          onClick: () => onDateClick(currentDay)
        }, /*#__PURE__*/React.createElement("div", {
          className: styles.dayLabel
        }, format(currentDay, dayFormat)), /*#__PURE__*/React.createElement("div", {
          className: styles.dateLabel
        }, format(currentDay, dateFormat))));
      }

      months.push( /*#__PURE__*/React.createElement("div", {
        className: styles.monthContainer,
        key: month
      }, /*#__PURE__*/React.createElement("span", {
        className: styles.monthYearLabel,
        style: labelColor
      }, format(month, labelFormat || "MMMM yyyy")), /*#__PURE__*/React.createElement("div", {
        className: styles.daysContainer,
        style: i === 0 ? firstSection : null
      }, days)));
      days = [];
    }

    return /*#__PURE__*/React.createElement("div", {
      id: "container",
      className: styles.dateListScrollable
    }, months);
  };

  const onDateClick = day => {
    setSelectedDate(day);

    if (getSelectedDay) {
      getSelectedDay(day);
    }
  };

  useEffect(() => {
    if (getSelectedDay) {
      if (selectDate) {
        getSelectedDay(selectDate);
      } else {
        getSelectedDay(startDate);
      }
    }
  }, []);
  useEffect(() => {
    if (selectDate) {
      if (!isSameDay(selectedDate, selectDate)) {
        setSelectedDate(selectDate);
        setTimeout(() => {
          let view = document.getElementById('selected');

          if (view) {
            view.scrollIntoView({
              behavior: "smooth",
              inline: "center",
              block: "nearest"
            });
          }
        }, 20);
      }
    }
  }, [selectDate]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, renderDays());
}
Example #16
Source File: MonthView.js    From react-horizontal-datepicker with MIT License 4 votes vote down vote up
MonthView = ({
  startDate,
  lastDate,
  selectDate,
  getSelectedDay,
  primaryColor,
  labelFormat
}) => {
  const [selectedDate, setSelectedDate] = useState(null);
  const rgb = primaryColor.replace(/[^\d,]/g, '').split(',');
  const brightness = Math.round((parseInt(rgb[0]) * 299 + parseInt(rgb[1]) * 587 + parseInt(rgb[2]) * 114) / 1000);
  const textColour = brightness > 125 ? 'black' : 'white';
  const selectedStyle = {
    borderRadius: "0.7rem",
    background: `${primaryColor}`,
    color: textColour
  };

  const getStyles = day => {
    return isSameDay(day, selectedDate) ? selectedStyle : null;
  };

  const getId = day => {
    return isSameDay(day, selectedDate) ? 'selected' : "";
  };

  const renderDays = () => {
    const months = [];

    for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
      const month = startOfMonth(addMonths(startDate, i));
      months.push( /*#__PURE__*/React.createElement("div", {
        id: `${getId(month)}`,
        className: styles.monthContainer,
        key: month,
        style: getStyles(month),
        onClick: () => onDateClick(month)
      }, /*#__PURE__*/React.createElement("span", {
        className: styles.monthYearLabel
      }, format(month, labelFormat || "MMMM yyyy"))));
    }

    return /*#__PURE__*/React.createElement("div", {
      id: "container",
      className: styles.dateListScrollable
    }, months);
  };

  const onDateClick = day => {
    setSelectedDate(day);

    if (getSelectedDay) {
      getSelectedDay(day);
    }
  };

  useEffect(() => {
    if (getSelectedDay) {
      if (selectDate) {
        getSelectedDay(selectDate);
      } else {
        getSelectedDay(startDate);
      }
    }
  }, []);
  useEffect(() => {
    if (selectDate) {
      if (!isSameDay(selectedDate, selectDate)) {
        setSelectedDate(selectDate);
        setTimeout(() => {
          let view = document.getElementById('selected');

          if (view) {
            view.scrollIntoView({
              behavior: "smooth",
              inline: "center",
              block: "nearest"
            });
          }
        }, 20);
      }
    }
  }, [selectDate]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, renderDays());
}
Example #17
Source File: DateView.js    From react-horizontal-datepicker with MIT License 4 votes vote down vote up
DateView = ({startDate, lastDate, selectDate, getSelectedDay, primaryColor, labelFormat, marked}) => {
    const [selectedDate, setSelectedDate] = useState(null);
    const firstSection = {marginLeft: '40px'};
    const selectedStyle = {fontWeight:"bold",width:"45px",height:"45px",borderRadius:"50%",border:`2px solid ${primaryColor}`,color:primaryColor};
    const labelColor = {color: primaryColor};
    const markedStyle = {color: "#8c3737", padding: "2px", fontSize: 12};

    const getStyles = (day) => {
        return isSameDay(day, selectedDate)?selectedStyle:null;
    };

    const getId = (day) => {
        return isSameDay(day, selectedDate)?'selected':"";
    };

    const getMarked = (day) => {
        let markedRes = marked.find(i => isSameDay(i.date, day));
        if (markedRes) {
            if (!markedRes?.marked) {
                return;
            }

            return <div style={{ ...markedRes?.style ?? markedStyle }} className={styles.markedLabel}>
                {markedRes.text}
            </div>;
        }

        return "";
    };

    const renderDays = () => {
        const dayFormat = "E";
        const dateFormat = "d";

        const months = [];
        let days = [];

        // const styleItemMarked = marked ? styles.dateDayItemMarked : styles.dateDayItem;

        for (let i = 0; i <= differenceInMonths(lastDate, startDate); i++) {
            let start, end;
            const month = startOfMonth(addMonths(startDate, i));

            start = i === 0 ? Number(format(startDate, dateFormat)) - 1 : 0;
            end = i === differenceInMonths(lastDate, startDate) ? Number(format(lastDate, "d")) : Number(format(lastDayOfMonth(month), "d"));

            for (let j = start; j < end; j++) {
                let currentDay = addDays(month, j);

                days.push(
                    <div id={`${getId(currentDay)}`}
                         className={marked ? styles.dateDayItemMarked : styles.dateDayItem}
                         style={getStyles(currentDay)}
                         key={currentDay}
                         onClick={() => onDateClick(currentDay)}
                    >
                        <div className={styles.dayLabel}>{format(currentDay, dayFormat)}</div>
                        <div className={styles.dateLabel}>{format(currentDay, dateFormat)}</div>
                        {getMarked(currentDay)}
                    </div>
                );
            }
            months.push(
                <div className={styles.monthContainer}
                     key={month}
                >
                    <span className={styles.monthYearLabel} style={labelColor}>
                        {format(month, labelFormat || "MMMM yyyy")}
                    </span>
                    <div className={styles.daysContainer} style={i===0?firstSection:null}>
                        {days}
                    </div>
                </div>
            );
            days = [];

        }

        return <div id={"container"} className={styles.dateListScrollable}>{months}</div>;
    }

    const onDateClick = day => {
        setSelectedDate(day);
        if (getSelectedDay) {
            getSelectedDay(day);
        }
    };

    useEffect(() => {
        if (getSelectedDay) {
            if (selectDate) {
                getSelectedDay(selectDate);
            } else {
                getSelectedDay(startDate);
            }
        }
    }, []);

    useEffect(() => {
        if (selectDate) {
            if (!isSameDay(selectedDate, selectDate)) {
                setSelectedDate(selectDate);
                setTimeout(() => {
                    let view = document.getElementById('selected');
                    if (view) {
                        view.scrollIntoView({behavior: "smooth", inline: "center", block: "nearest"});
                    }
                }, 20);
            }
        }
    }, [selectDate]);

    return <React.Fragment>{renderDays()}</React.Fragment>
}
Example #18
Source File: DateRangePickerCalendar.js    From react-nice-dates with MIT License 4 votes vote down vote up
export default function DateRangePickerCalendar({
  locale,
  startDate,
  endDate,
  focus,
  month: receivedMonth,
  onStartDateChange,
  onEndDateChange,
  onFocusChange,
  onMonthChange,
  minimumDate,
  maximumDate,
  minimumLength,
  maximumLength,
  modifiers: receivedModifiers,
  modifiersClassNames,
  weekdayFormat,
  touchDragEnabled
}) {
  const [hoveredDate, setHoveredDate] = useState()
  const [month, setMonth] = useControllableState(
    receivedMonth,
    onMonthChange,
    startOfMonth(startDate || endDate || new Date())
  )

  const displayedStartDate =
    focus === START_DATE && !startDate && endDate && hoveredDate && !isSameDay(hoveredDate, endDate)
      ? hoveredDate
      : startOfDay(startDate)

  const displayedEndDate =
    focus === END_DATE && !endDate && startDate && hoveredDate && !isSameDay(hoveredDate, startDate)
      ? hoveredDate
      : startOfDay(endDate)

  const isStartDate = date => isSameDay(date, displayedStartDate) && isBefore(date, displayedEndDate)
  const isMiddleDate = date => isAfter(date, displayedStartDate) && isBefore(date, displayedEndDate)
  const isEndDate = date => isSameDay(date, displayedEndDate) && isAfter(date, displayedStartDate)

  const modifiers = mergeModifiers(
    {
      selected: date =>
        isSelectable(date, { minimumDate, maximumDate }) &&
        (isStartDate(date) ||
          isMiddleDate(date) ||
          isEndDate(date) ||
          isSameDay(date, startDate) ||
          isSameDay(date, endDate)),
      selectedStart: isStartDate,
      selectedMiddle: isMiddleDate,
      selectedEnd: isEndDate,
      disabled: date =>
        (focus === START_DATE &&
          endDate &&
          ((differenceInDays(startOfDay(endDate), date) < minimumLength && (!startDate || !isAfter(date, startOfDay(endDate)))) ||
            (!startDate && maximumLength && differenceInDays(startOfDay(endDate), date) > maximumLength))) ||
        (focus === END_DATE &&
          startDate &&
          ((differenceInDays(date, startOfDay(startDate)) < minimumLength && (!endDate || !isBefore(date, startOfDay(startDate)))) ||
            (!endDate && maximumLength && differenceInDays(date, startOfDay(startDate)) > maximumLength)))
    },
    receivedModifiers
  )

  const handleSelectDate = date => {
    if (focus === START_DATE) {
      const invalidEndDate =
        endDate && !isRangeLengthValid({ startDate: date, endDate }, { minimumLength, maximumLength })

      if (invalidEndDate) {
        onEndDateChange(null)
      }

      onStartDateChange(startDate ? setTime(date, startDate) : date)
      onFocusChange(END_DATE)
    } else if (focus === END_DATE) {
      const invalidStartDate =
        startDate && !isRangeLengthValid({ startDate, endDate: date }, { minimumLength, maximumLength })

      if (invalidStartDate) {
        onStartDateChange(null)
      }

      onEndDateChange(endDate ? setTime(date, endDate) : date)
      onFocusChange(invalidStartDate || !startDate ? START_DATE : null)
    }
  }

  return (
    <Calendar
      locale={locale}
      month={month}
      onMonthChange={setMonth}
      onDayHover={setHoveredDate}
      onDayClick={handleSelectDate}
      minimumDate={minimumDate}
      maximumDate={maximumDate}
      modifiers={modifiers}
      modifiersClassNames={modifiersClassNames}
      weekdayFormat={weekdayFormat}
      touchDragEnabled={touchDragEnabled}
    />
  )
}
Example #19
Source File: Calendar.js    From covid19india-react with MIT License 4 votes vote down vote up
function Calendar({date, dates, slider}) {
  const [view, setView] = useState('month');
  const [activeStartDate, setActiveStartDate] = useState(parseIndiaDate(date));

  const minDate = parseIndiaDate(dates[0]);
  const maxDate = parseIndiaDate(dates[dates.length - 1]);

  const isDateDisabled = ({date, view}) => {
    return (
      view === 'month' &&
      !dates.includes(formatISO(date, {representation: 'date'}))
    );
  };

  const handleCalendarClick = (value) => {
    const clickedDate = formatISO(value, {representation: 'date'});
    slider.moveToSlide(dates.indexOf(clickedDate));
  };

  const handleViewButton = ({view}) => {
    setView(view);
  };

  const handleNavigationButton = ({activeStartDate}) => {
    setActiveStartDate(activeStartDate);
  };

  const handleNavigation = (direction) => {
    const newDate = add(
      activeStartDate,
      view === 'month' ? {months: direction} : {years: direction}
    );
    const lower =
      view === 'month' ? startOfMonth(minDate) : startOfYear(minDate);
    const upper = view === 'month' ? endOfMonth(maxDate) : endOfYear(maxDate);
    if (lower <= newDate && newDate <= upper) {
      setActiveStartDate(newDate);
    }
  };

  const swipeHandlers = useSwipeable({
    onSwipedRight: handleNavigation.bind(this, -1),
    onSwipedLeft: handleNavigation.bind(this, 1),
  });

  const handleWheel = (event) => {
    if (event.deltaX !== 0) {
      handleNavigation(Math.sign(event.deltaX));
    }
  };

  return (
    <div className="Calendar" onWheel={handleWheel} {...swipeHandlers}>
      <ReactCalendar
        value={parseIndiaDate(date)}
        tileDisabled={isDateDisabled}
        {...{minDate, maxDate, activeStartDate, view}}
        onActiveStartDateChange={handleNavigationButton}
        onViewChange={handleViewButton}
        minDetail="year"
        showFixedNumberOfWeeks
        onChange={handleCalendarClick}
        prevLabel={
          <div>
            <ChevronLeft size={18} />
          </div>
        }
        nextLabel={
          <div>
            <ChevronRight size={18} />
          </div>
        }
        prev2Label={
          <div>
            <ChevronsLeft size={18} />
          </div>
        }
        next2Label={
          <div>
            <ChevronsRight size={18} />
          </div>
        }
      />
    </div>
  );
}