import React, { useState } from "react"; import { getEnumKeyByEnumValue, QUESTION_TYPES } from "../commons"; import { getElementByQuestionType } from "../helpers"; import { IQuestionProps } from "../types"; import { useDrag, useDrop } from "react-dnd"; import { SurveyLayout } from "../layouts"; import { surveyApi } from "../apis"; const options = Object.entries(QUESTION_TYPES).map(([type, value]) => ( {value} )); export interface DropResult { name: string; } export const Question = ({ element, handleQuestion, deleteQuestion, }: IQuestionProps) => { const [question, setQuestion] = useState(element); const isEditing = question.isEditing; async function handleEditComplete() { 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); } }); } function handleSelect(event: React.ChangeEvent) { 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) { 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 }); }; // const [{ isDragging }, drag] = useDrag(() => ({ type: SurveyLayout.name, item: { name: question.type }, end: (item, monitor) => { const dropResult = monitor.getDropResult(); 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; } }, })); // return ( {getElementByQuestionType(question, handleElement, isEditing)} {options} 필수 {isEditing ? ( <> 취소 확인 > ) : ( <> 삭제 수정 > )} ); };