import React, { useState, memo, useCallback, useEffect, useRef } from 'react'; import Glyphicon from 'react-bootstrap/lib/Glyphicon'; import Button from 'react-bootstrap/lib/Button'; import moment from 'moment'; import classnames from 'classnames'; import keycode from 'keycode'; import { uncontrollable } from 'uncontrollable'; import styled from 'styled-components'; export const defaultDateFormat = 'YYYY-MM-DD'; const StyledDiv = styled.div` text-align: center; display: inline-block; .calendar-nav { text-align: center; } .calendar-table { margin-left: auto; margin-right: auto; cursor: pointer; td, th { width: 100% /7; padding: 0 2px; } td.not-this-month { color: #999; } td:hover { background-color: #eee; } td.selected { background-color: #ccc; } &.disabled { cursor: not-allowed; td:hover { background-color: transparent; } td.selected { background-color: #ddd; } } } `; export interface YearMonth { year: number; month: number; } const ControlledCalendar: React.FC<{ value: any; onChange: any; format?: string; disabled?: boolean; yearMonth: YearMonth; onYearMonthChange: (yearMonth: YearMonth) => void; }> = props => { const { value, onChange, format = defaultDateFormat, disabled, yearMonth, onYearMonthChange } = props; const resolveYearMonthProp = () => { const ym = yearMonth; if (ym != undefined && ym.year && ym.month >= 1 && ym.month <= 12) { return ym; } const date = new Date(); return { year: date.getFullYear(), month: date.getMonth() + 1 }; }; const { year, month } = resolveYearMonthProp(); const nav = useCallback( (delta, unit) => { if (typeof onYearMonthChange !== 'function') return; const newDate = moment({ year, month: month - 1 }).add(delta, unit); onYearMonthChange({ year: newDate.year(), month: newDate.month() + 1 }); }, [month, year, onYearMonthChange] ); const divRef = useRef(null); const prevYear = useCallback(() => nav(-1, 'year'), [nav]); const nextYear = useCallback(() => nav(+1, 'year'), [nav]); const prevMonth = useCallback(() => nav(-1, 'month'), [nav]); const nextMonth = useCallback(() => nav(+1, 'month'), [nav]); useEffect(() => { const handleWheel = (ev: WheelEvent) => { if (disabled) return; ev.preventDefault(); if (ev.deltaY > 0) nextMonth(); if (ev.deltaY < 0) prevMonth(); }; const div = divRef.current!; div.addEventListener('wheel', handleWheel, { passive: false }); return () => { div.removeEventListener('wheel', handleWheel); }; }, [year, month, disabled, nextMonth, prevMonth]); return (
{year} - {month}
); }; // uncontrollable makes this component 'optionally-controllable'. export const Calendar = uncontrollable(ControlledCalendar, { yearMonth: 'onYearMonthChange' }); export default Calendar; const Navicon: React.FC<{ glyph: string; onClick: () => void; disabled?: boolean; }> = ({ glyph, onClick, disabled }) => ( ); const split = (array: T[], every: number): T[][] => { const result = []; let i = 0; while (i < array.length) { result.push(array.slice(i, i + every)); i += every; } return result; }; const CalendarTable: React.FC<{ value: string; onChange?: (value: string) => void; disabled?: boolean; yearMonth: YearMonth; format: string; }> = React.memo(props => { const [hasFocus, setHasFocus] = useState(false); const { yearMonth: { year, month }, value, disabled, onChange, format = defaultDateFormat } = props; const tbodyRef = useRef(null); const tableRef = useRef(null); const handleDateSelect = useCallback( ev => { if (disabled) return; const date = moment.unix(ev.target.dataset.date); if (typeof onChange === 'function') { onChange(date.format(format)); } }, [disabled, format, onChange] ); const focusRelative = useCallback((ev, delta) => { const children = Array.from(tbodyRef.current!.querySelectorAll('td')); const fromDate = moment.unix(ev.target.dataset.date); const toDate = fromDate.add(delta, 'day').unix(); const nextNode = children.find(el => el.dataset.date === String(toDate)); if (nextNode) { nextNode.focus(); ev.preventDefault(); ev.stopPropagation(); } }, []); const handleTableFocus = useCallback( ev => { const children = Array.from(tbodyRef.current!.querySelectorAll('td')); if (ev.target === tableRef.current) { const valueMoment = value !== undefined ? moment(value, format).unix() : undefined; const selected = children.find( el => el.dataset.date === String(valueMoment) ); if (selected) selected.focus(); else tbodyRef.current!.querySelector('td')!.focus(); } setHasFocus(true); }, [format, value] ); const handleTableBlur = useCallback(() => setHasFocus(false), []); const handleKeyDown = useCallback( ev => { const key = keycode(ev); switch (key) { case 'enter': case 'space': handleDateSelect(ev); ev.preventDefault(); break; case 'right': focusRelative(ev, 1); break; case 'left': focusRelative(ev, -1); break; case 'up': focusRelative(ev, -7); break; case 'down': focusRelative(ev, 7); break; } }, [focusRelative, handleDateSelect] ); if (!year || !month) return
Invalid year month
; const start = moment({ year, month: month - 1, day: 1 }).startOf('week'); const last = moment({ year, month: month - 1 }) .endOf('month') .endOf('week') .startOf('day'); const lastTimestamp = last.unix(); const valueMoment = value !== undefined ? moment(value, format) : undefined; const days = []; let i = 0; for (;;) { const date = start.clone().add(i, 'day'); days.push(date); if (date.unix() >= lastTimestamp) break; i++; } const weeks = split(days, 7); const day = (date: moment.Moment) => { const classNames = classnames({ selected: valueMoment && date.isSame(valueMoment, 'day'), 'not-this-month': date.month() !== month - 1 }); return ( {date.date()} ); }; const classNames = classnames('calendar-table', { 'text-muted': disabled, disabled }); return ( {weeks.map(week => ( {week.map(date => day(date))} ))}
Su Mo Tu We Th Fr Sa
); });