SideSubject.js 2.55 KB
import { useRef, useState } from "react";

const SideSubject = ({ subject, dispatch }) => {
  const defaultColor = "#EFEFEF";
  const [state, setState] = useState({
    nickname: subject.nickname || subject.name,
    color: subject.color,
  });

  const handleChangeState = (e) => {
    setState({
      ...state,
      [e.target.name]: e.target.value,
    });
  };

  const check = (e) => {
    dispatch({ type: "CHECKED", subjectID: subject.subjectID });
    if (subject.status) e.target.style["background-color"] = defaultColor;
    else e.target.style["background-color"] = subject.color;
  };

  const popupRef = useRef();

  const labelClick = (e) => {
    popupRef.current.style.display = "flex";
  };

  const popupClose = (e) => {
    setState({
      nickname: subject.nickname || subject.name,
      color: subject.color,
    });
    popupRef.current.style.display = "none";
  };

  const popupApply = (e) => {
    if (state.nickname.length < 1) alert("이름을 입력해 주세요");
    else if (state.color.length !== 6) alert("색상은 6자리 16진수 값 입니다");
    else {
      let check = true;
      for (const c of state.color) if (isNaN(parseInt(c, 16))) check = false;
      if (!check) alert("색상은 16진수 값 입니다");
      else {
        dispatch({
          type: "MODIFY",
          subjectID: subject.subjectID,
          nickname: state.nickname,
          color: state.color,
        });
        e.target.offsetParent.style.display = "none";
      }
    }
  };

  return (
    <div className="SideSubject">
      <div
        className="ssc"
        onClick={check}
        style={{
          backgroundColor: subject.status ? "#" + subject.color : defaultColor,
        }}
      ></div>
      <span className="ssl" onClick={labelClick}>
        {subject.nickname || subject.name}
      </span>
      <div className="ss_popup" ref={popupRef}>
        <div className="sspd">
          <div className="sspd_1">
            <span>이름</span>
            <input
              name="nickname"
              value={state.nickname}
              onChange={handleChangeState}
            />
          </div>
          <div className="sspd_2">
            <span>색상</span>
            <input
              name="color"
              value={state.color}
              onChange={handleChangeState}
            />
          </div>
        </div>
        <div className="ssp_btns">
          <button onClick={popupApply}>적용 </button>
          <button onClick={popupClose}>취소</button>
        </div>
      </div>
    </div>
  );
};

export default SideSubject;