2022-02-12 16:25:44 -05:00
|
|
|
import React from 'react';
|
2022-02-12 13:02:31 -05:00
|
|
|
import {Calendar} from './Calendar';
|
2022-02-12 18:03:28 -05:00
|
|
|
import {frSupportedYear, gregorianJDN, jdnFrench, Month} from './dates';
|
2022-02-12 09:44:58 -05:00
|
|
|
|
2022-02-12 16:25:44 -05:00
|
|
|
type YearMonth = {
|
|
|
|
year: number;
|
|
|
|
month: Month;
|
|
|
|
}
|
|
|
|
|
|
|
|
function parseURL(): YearMonth | null {
|
|
|
|
const match = /\/(-?\d+)\/(\d+)/.exec(window.location.pathname);
|
|
|
|
if (!match)
|
|
|
|
return null;
|
|
|
|
|
|
|
|
const month = +match[2];
|
2022-02-12 17:58:54 -05:00
|
|
|
const year = +match[1];
|
|
|
|
if (!frSupportedYear(year) || month < 1 || month > 13)
|
2022-02-12 16:25:44 -05:00
|
|
|
return null;
|
2022-02-12 17:58:54 -05:00
|
|
|
return {year: year, month: month as Month};
|
2022-02-12 16:25:44 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
type AppState = YearMonth & {
|
|
|
|
todayJDN: number,
|
|
|
|
};
|
|
|
|
|
|
|
|
class App extends React.Component<{}, AppState> {
|
|
|
|
state: AppState;
|
|
|
|
|
|
|
|
constructor(props: {}) {
|
|
|
|
super(props);
|
|
|
|
const today = new Date();
|
2022-02-12 18:45:57 -05:00
|
|
|
const todayJDN = gregorianJDN(today.getFullYear(), today.getMonth() + 1, today.getDate());
|
2022-02-12 16:42:29 -05:00
|
|
|
const {year, month} = jdnFrench(todayJDN);
|
2022-02-12 16:25:44 -05:00
|
|
|
|
|
|
|
this.state = {
|
2022-02-12 16:42:29 -05:00
|
|
|
...(parseURL() || {year, month}),
|
|
|
|
todayJDN,
|
2022-02-12 16:25:44 -05:00
|
|
|
};
|
|
|
|
this.updateURL();
|
|
|
|
this.updateStateFromURL = this.updateStateFromURL.bind(this);
|
|
|
|
}
|
|
|
|
|
|
|
|
componentDidMount() {
|
|
|
|
window.addEventListener('popstate', this.updateStateFromURL);
|
|
|
|
}
|
|
|
|
|
|
|
|
componentWillUnmount() {
|
|
|
|
window.removeEventListener('popstate', this.updateStateFromURL);
|
|
|
|
}
|
|
|
|
|
|
|
|
private updateStateFromURL(event: PopStateEvent) {
|
|
|
|
this.setState(event.state);
|
|
|
|
}
|
|
|
|
|
|
|
|
private updateURL() {
|
|
|
|
const {year, month} = this.state;
|
|
|
|
const path = `/${year}/${month}`;
|
|
|
|
if (path !== window.location.pathname) {
|
|
|
|
window.history.pushState({year, month}, '', path);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
setState(state: any, callback?: () => void) {
|
|
|
|
super.setState(state, () => {
|
|
|
|
this.updateURL();
|
|
|
|
callback && callback();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
render() {
|
|
|
|
return <Calendar
|
|
|
|
year={this.state.year} month={this.state.month} todayJDN={this.state.todayJDN}
|
|
|
|
onSwitch={(year, month) => {
|
|
|
|
this.setState({year, month})
|
|
|
|
}}/>;
|
|
|
|
}
|
2022-02-12 09:44:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export default App;
|