Files
aurora-admin/frameworks/Calendar.jsx
T

69 lines
2.6 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useState, useMemo } from 'react';
import './Calendar.css';
const WEEKS = ['日', '一', '二', '三', '四', '五', '六'];
function fmt(dt) {
const p = x => (x < 10 ? '0' + x : '' + x);
return dt.getFullYear() + '-' + p(dt.getMonth() + 1) + '-' + p(dt.getDate());
}
export default function Calendar({ value = '', onChange }) {
const now = new Date();
const [viewY, setViewY] = useState(now.getFullYear());
const [viewM, setViewM] = useState(now.getMonth());
const [selected, setSelected] = useState(value);
const today = fmt(now);
const cells = useMemo(() => {
const first = new Date(viewY, viewM, 1).getDay();
const days = new Date(viewY, viewM + 1, 0).getDate();
const prevDays = new Date(viewY, viewM, 0).getDate();
const arr = [];
for (let i = 0; i < first; i++) {
let pd = prevDays - first + 1 + i, pm = viewM - 1, py = viewY;
if (pm < 0) { pm = 11; py--; }
arr.push({ day: pd, out: true, key: fmt(new Date(py, pm, pd)) });
}
for (let d = 1; d <= days; d++) {
const k = fmt(new Date(viewY, viewM, d));
arr.push({ day: d, out: false, today: k === today, key: k });
}
const tail = (7 - (arr.length % 7)) % 7;
for (let t = 1; t <= tail; t++) {
let nm = viewM + 1, ny = viewY; if (nm > 11) { nm = 0; ny++; }
arr.push({ day: t, out: true, key: fmt(new Date(ny, nm, t)) });
}
return arr;
}, [viewY, viewM, today]);
function prev() { let m = viewM - 1, y = viewY; if (m < 0) { m = 11; y--; } setViewM(m); setViewY(y); }
function next() { let m = viewM + 1, y = viewY; if (m > 11) { m = 0; y++; } setViewM(m); setViewY(y); }
function pick(c) {
setSelected(c.key);
setViewY(parseInt(c.key.slice(0, 4), 10));
setViewM(parseInt(c.key.slice(5, 7), 10) - 1);
onChange && onChange(c.key);
}
return (
<div className="aa-calendar">
<div className="aa-calendar-head">
<button className="aa-calendar-nav" onClick={prev}>‹</button>
<span className="aa-calendar-title">{viewY} 年 {viewM + 1} 月</span>
<button className="aa-calendar-nav" onClick={next}>›</button>
</div>
<div className="aa-calendar-week">
{WEEKS.map(w => <span className="aa-calendar-weekday" key={w}>{w}</span>)}
</div>
<div className="aa-calendar-grid">
{cells.map((c, i) => (
<div key={i} className={'aa-calendar-cell' + (c.out ? ' is-out' : '') + (c.today ? ' is-today' : '') + (c.key === selected ? ' is-selected' : '')}
onClick={() => pick(c)}>
{c.day}
</div>
))}
</div>
</div>
);
}