Calendar.js 1.96 KB
import React, { useEffect, useReducer, useState } from "react";
import { Navigate, Route, Routes } from "react-router-dom";

import Month from "../components/Month";
import Header from "../components/Header";
import Side from "../components/Side";
import { initTempSubjects } from "../utils/Test";
import { subForage } from "../utils/LocalForage";

export const CalendarStateContext = React.createContext();

const render = (subsObj, args) => {
  switch (args.type) {
    case "CHECKED":
      const sub = subsObj[args.code];
      sub.selected = !sub.selected;
      subForage.setItem(args.code, sub);
      return { ...subsObj, [args.code]: sub };
    case "INIT":
      return args.subsObj;
    default:
      return subsObj;
  }
};

const Calendar = () => {
  console.log("visit Calendar");

  const session = localStorage.getItem("session");

  const [state, setState] = useState({
    scope: "month",
    date: new Date(),
  });
  const [subsObj, dispatch] = useReducer(render, {});

  useEffect(() => {
    async function initSubsObj() {
      if (!localStorage.getItem("Subjects")) await initTempSubjects();
      const subCodeLst = JSON.parse(localStorage.getItem("Subjects"));
      let tsubsObj = {};
      for (const code of subCodeLst) {
        tsubsObj[code] = await subForage.getItem(code);
      }
      dispatch({ type: "INIT", subsObj: tsubsObj });
    }
    initSubsObj();
  }, []);

  return (
    <CalendarStateContext.Provider
      value={{ state, setState, subsObj, dispatch }}
    >
      {session ? (
        <div className="Calendar">
          <Header />
          <div className="content">
            <Side />
            <Routes>
              <Route path="/month/*" element={<Month />} />
              <Route path="/week/*" element={<></>} />
              <Route path="/day/*" element={<></>} />
            </Routes>
          </div>
        </div>
      ) : (
        <Navigate to="/login" />
      )}
    </CalendarStateContext.Provider>
  );
};

export default Calendar;