Calendar.js 2.11 KB
import React, { 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";

export const CalendarStateContext = React.createContext();

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

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

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

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

  let subLst;
  if (!localStorage.getItem("Subjects")) {
    subLst = [];
    let tcolors = [
      "red",
      "green",
      "blue",
      "orange",
      "gold",
      "aqua",
      "chartreuse",
    ];
    for (let i = 0; i < 7; i++) {
      let code = i + 1;
      let tsub = { name: "과목" + code, color: tcolors[i], selected: true };
      subLst.push(code);
      localStorage.setItem("S" + code, JSON.stringify(tsub));
    }
    localStorage.setItem("Subjects", JSON.stringify(subLst));
  }

  subLst = JSON.parse(localStorage.getItem("Subjects"));
  let tsubsObj = {};
  for (const code of subLst) {
    tsubsObj[code] = JSON.parse(localStorage.getItem("S" + code));
  }

  const [subsObj, dispatch] = useReducer(render, tsubsObj);

  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;