Question.tsx 5.78 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
2
3
4
import React, { useState } from "react";
import { getEnumKeyByEnumValue, QUESTION_TYPES } from "../commons";
import { getElementByQuestionType } from "../helpers";
import { IQuestionProps } from "../types";
jang dong hyeok's avatar
jang dong hyeok committed
5
6
7
import { useDrag, useDrop } from "react-dnd";
import { SurveyLayout } from "../layouts";
import { surveyApi } from "../apis";
Yoon, Daeki's avatar
Yoon, Daeki committed
8
9
10
11
12
13
14

const options = Object.entries(QUESTION_TYPES).map(([type, value]) => (
  <option key={type} value={value}>
    {value}
  </option>
));

jang dong hyeok's avatar
jang dong hyeok committed
15
16
17
export interface DropResult {
  name: string;
}
Yoon, Daeki's avatar
Yoon, Daeki committed
18
19
20
21
22
23
24
25
export const Question = ({
  element,
  handleQuestion,
  deleteQuestion,
}: IQuestionProps) => {
  const [question, setQuestion] = useState(element);
  const isEditing = question.isEditing;

jang dong hyeok's avatar
jang dong hyeok committed
26
27
  const [questions, setQuestions] = useState();

Yoon, Daeki's avatar
Yoon, Daeki committed
28
  async function handleEditComplete() {
29
30
31
32
33
34
35
36
37
38
    question.content.choices.map((choice) => {
      if (choice.text.trim() === "") {
        alert("질문작성이 완료되지 않았습니다.");
        return (question.isEditing = true);
      } else {
        question.isEditing = false;
        console.log("editing completed:", question);
        handleQuestion(question);
      }
    });
Yoon, Daeki's avatar
Yoon, Daeki committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  }

  function handleSelect(event: React.ChangeEvent<HTMLSelectElement>) {
    const selectedType = event.currentTarget.value;
    console.log(selectedType);

    const selectedKind =
      getEnumKeyByEnumValue(QUESTION_TYPES, selectedType) ?? "singletext";
    console.log("selected kind:", selectedKind);
    setQuestion({ ...question, type: selectedKind });
  }

  const handleElement = () => {
    console.log("handle element");
    setQuestion({ ...question });
  };

  function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    const { checked, name, value } = event.currentTarget;
    if (name === "isRequired") {
      return setQuestion({ ...question, [name]: checked });
    }
    setQuestion({ ...question, [name]: value });
  }

  const onCancel = () => {
    const originalQuestion = { ...element, isEditing: false };
    setQuestion(originalQuestion);
    handleQuestion(originalQuestion);
  };

  const onDelete = () => {
    if (window.confirm("질문을 삭제하시겠습니까?")) {
      deleteQuestion(question._id);
    }
  };

  const onEdit = () => {
    setQuestion({ ...question, isEditing: true });
    handleQuestion({ ...question, isEditing: true });
  };
jang dong hyeok's avatar
jang dong hyeok committed
80
  //
Yoon, Daeki's avatar
Yoon, Daeki committed
81

jang dong hyeok's avatar
jang dong hyeok committed
82
83
84
85
86
87
88
  const [{ isDragging }, drag] = useDrag(() => ({
    type: SurveyLayout.name,
    item: { name: question.type },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult<DropResult>();
      if (item && dropResult) {
        alert(`You dropped ${item.name}`);
jang dong hyeok's avatar
jang dong hyeok committed
89
90
      } else {
        alert("you dropped wrong place");
jang dong hyeok's avatar
jang dong hyeok committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
      }
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  }));

  const [{ canDrop, isOver }, drop] = useDrop(() => ({
    accept: SurveyLayout.name,
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  }));

  //
Yoon, Daeki's avatar
Yoon, Daeki committed
107
  return (
jang dong hyeok's avatar
jang dong hyeok committed
108
109
110
111
112
113
114
    <div
      ref={drop}
      className="flex w-4/5 h-full justify-center"
      style={{
        border: isOver ? "dotted" : "",
      }}
    >
jang dong hyeok's avatar
jang dong hyeok committed
115
116
      <div
        ref={drag}
jang dong hyeok's avatar
jang dong hyeok committed
117
118
119
        style={{
          borderColor: isEditing ? "red" : "#0A8A8A",
        }}
jang dong hyeok's avatar
jang dong hyeok committed
120
121
122
123
124
        className={
          "flex flex-col container w-full h-auto border-2 items-center m-3 py-2 rounded-lg cursor-move "
        }
      >
        <div className="flex h-16 w-full place-content-center items-center">
Yoon, Daeki's avatar
Yoon, Daeki committed
125
          <input
jang dong hyeok's avatar
jang dong hyeok committed
126
127
128
129
130
131
            type="text"
            name="title"
            id={question._id}
            className="text-xl font-bold border-b-2 w-11/12"
            placeholder={"Question Title"}
            value={question.title}
Yoon, Daeki's avatar
Yoon, Daeki committed
132
133
            onChange={handleChange}
            disabled={!isEditing}
jang dong hyeok's avatar
jang dong hyeok committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
          ></input>
        </div>
        <div className="flex w-full justify-center">
          <input
            type="text"
            name="comment"
            id={question._id}
            className="border w-11/12"
            placeholder="질문에 대한 설명을 입력해주세요"
            value={question.comment}
            onChange={handleChange}
            disabled={!isEditing}
          ></input>
        </div>
        {getElementByQuestionType(question, handleElement, isEditing)}
        <div className="flex flex-row place-content-between w-11/12 py-2">
          <select
            id={question._id}
            name="type"
            onChange={handleSelect}
            disabled={!isEditing}
            value={QUESTION_TYPES[question.type]}
            className="w-32 h-10 md:w-36 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-themeColor"
          >
            {options}
          </select>
          <div className="place-self-end py-2">
            <input
              type="checkbox"
              id="isRequired"
              name="isRequired"
              onChange={handleChange}
              disabled={!isEditing}
              checked={question.isRequired}
            />
            <label htmlFor="isRequired" className="px-1">
              필수
            </label>
            {isEditing ? (
              <>
                <button type="button" className="px-1" onClick={onCancel}>
                  취소
                </button>
Yoon, Daeki's avatar
Yoon, Daeki committed
177

jang dong hyeok's avatar
jang dong hyeok committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
                <button
                  type="button"
                  className="px-1"
                  onClick={handleEditComplete}
                >
                  확인
                </button>
              </>
            ) : (
              <>
                <button type="button" className="px-1" onClick={onDelete}>
                  삭제
                </button>
                <button type="button" className="px-1" onClick={onEdit}>
                  수정
                </button>
              </>
            )}
          </div>
Yoon, Daeki's avatar
Yoon, Daeki committed
197
198
199
200
201
        </div>
      </div>
    </div>
  );
};