Question.tsx 5.7 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
26
export const Question = ({
  element,
  handleQuestion,
  deleteQuestion,
}: IQuestionProps) => {
  const [question, setQuestion] = useState(element);
  const isEditing = question.isEditing;

  async function handleEditComplete() {
27
28
29
30
31
32
33
34
35
36
    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
37
38
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
  }

  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
78
  //
Yoon, Daeki's avatar
Yoon, Daeki committed
79

jang dong hyeok's avatar
jang dong hyeok committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
  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}`);
      }
    },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
      handlerId: monitor.getHandlerId(),
    }),
  }));

  const [{ canDrop, isOver }, drop] = useDrop(() => ({
    accept: SurveyLayout.name,
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
    hover(item, monitor) {
      if (!isDragging) {
        return;
      }
    },
  }));

  //
Yoon, Daeki's avatar
Yoon, Daeki committed
109
  return (
jang dong hyeok's avatar
jang dong hyeok committed
110
    <div ref={drop} className="flex w-full h-full justify-center">
jang dong hyeok's avatar
jang dong hyeok committed
111
112
113
114
115
116
117
118
      <div
        ref={drag}
        style={{ borderColor: isEditing ? "red" : "#0A8A8A" }}
        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
119
          <input
jang dong hyeok's avatar
jang dong hyeok committed
120
121
122
123
124
125
            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
126
127
            onChange={handleChange}
            disabled={!isEditing}
jang dong hyeok's avatar
jang dong hyeok committed
128
129
130
131
132
133
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
          ></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
171

jang dong hyeok's avatar
jang dong hyeok committed
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
                <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
191
192
193
194
195
        </div>
      </div>
    </div>
  );
};