Skip to content
Snippets Groups Projects
Commit 29914a16 authored by Gaeon Kim's avatar Gaeon Kim
Browse files

feat: main.js

parent c559a48d
No related branches found
No related tags found
No related merge requests found
import React, {useEffect, useState} from 'react';
import '@progress/kendo-react-intl';
import '@progress/kendo-react-scheduler';
import { Scheduler, WeekView, DayView, MonthView, WorkWeekView} from '@progress/kendo-react-scheduler';
import main_styles from './main.module.css'
import ScheduleAddModal from './addModal'
import ScheduleDeleteModal from './deleteModal';
import ScheduleInquiryModal from './inquiryModal';
// import '@progress/kendo-react-intl/dist/es/all';
// import '@progress/kendo-react-scheduler/dist/es/views/week/WeekView' // 한글 지역화 파일s
// import { IntlProvider, load, LocalizationProvider, IntlService } from '@progress/kendo-react-intl';
import Header from './Header'
const MySchedulerApp = () => {
useEffect(() => {
// 페이지가 로드되면 실행될 코드
const headingCell1 = document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(1)');
const headingCell2 = document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(2)');
const headingCell3 = document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(3)');
const headingCell4 = document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(4)');
const headingCell5 = document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(5)');
const headingCell6= document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(6)');
const headingCell7= document.querySelector('.k-scheduler-cell .k-heading-cell:nth-child(7)');
if (headingCell1) {
headingCell1.textContent = "";
}
if (headingCell2) {
headingCell2.textContent = "";
}
if (headingCell3) {
headingCell3.textContent = "";
}
if (headingCell4) {
headingCell4.textContent = "";
}
if (headingCell5) {
headingCell5.textContent = "";
}
if (headingCell6) {
headingCell6.textContent = "";
}
if (headingCell7) {
headingCell7.textContent = "";
}
}, []);
const [scheduleData, setScheduleData] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isInModalOpen, setIsInModalOpen] = useState(false);
const [isDeModalOpen, setIsDeModalOpen]=useState(false);
const [selectedSchedule, setSelectedSchedule] = useState(null);
const [weeklySchedules, setWeeklySchedules] = useState([]);
const[selectedDate, setSelectedDate]=useState(new Date());
const openInModal=()=>{
//일정 조회 모달 열기
setIsInModalOpen(true);
}
const openModal = () => {
// 일정 추가 모달 열기
setIsModalOpen(true);
};
const openDeModal=()=>{
//일정 삭제 모달 열기
setIsDeModalOpen(true);
console.log('isDeModalOpen:', isDeModalOpen);
}
const closeModal = () => {
// 일정 추가 모달 닫기
setIsModalOpen(false);
};
const closeInModal = () => {
// 일정 조회 모달 닫기
setIsInModalOpen(false);
};
const closeDeModal = () => {
// 일정 삭제 모달 닫기
setIsDeModalOpen(false);
console.log('isDeModalOpen:', isDeModalOpen);
};
const handleSaveEvent = (formData) => {
// 일정 저장 및 모달 닫기
const jsonData=JSON.stringify(formData);
console.log('Sending data to the server:', jsonData);
// 백엔드로 데이터 전송 (Fetch API 사용)
fetch('/scheduler', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: jsonData,
})
.then(response => response.json())
.then(data => {
// 성공 시 처리
console.log(data);
})
.catch(error => {
// 실패 시 처리
console.error(error);
});
// 모달 닫기
setScheduleData((prevData) => [...prevData, formData])
closeModal();
};
const handleInquiryEvent=async(date)=>{
try {
setSelectedDate(date.InquiryDate);
const formattedDate = date.InquiryDate.toISOString().split('T')[0];
const response = await fetch(`/api/schedules/dates?date=${formattedDate}`);
const data = await response.json();
const processedDataArray = [];
for (const backendData of data) {
// 백엔드에서 받아온 데이터의 날짜 정보를 사용하여 Date 객체 생성
const startDate = new Date(backendData.date);
// "14:00" 형식의 문자열을 받아 현재 날짜에 추가
const startTimeParts = backendData.startTime.split(':');
const endTimeParts = backendData.endTime.split(':');
const startTime = new Date(startDate);
const endTime=new Date(startDate);
const clr=backendData.color;
startTime.setHours(parseInt(startTimeParts[0], 10));
startTime.setMinutes(parseInt(startTimeParts[1], 10));
endTime.setHours(parseInt(endTimeParts[0], 10));
endTime.setMinutes(parseInt(endTimeParts[1], 10));
processedDataArray.push({
id: backendData.id,
date: backendData.date,
start:startTime,
end: endTime,
title: backendData.title,
color:clr,
description: backendData.Description
});
}
setScheduleData(processedDataArray);
} catch (error) {
console.error('Error fetching weekly schedules:', error);
}
};
useEffect(() => {
// 페이지가 로드되면 백엔드에서 일정 데이터를 가져와서 설정
// const backendEndpoint = '/api/schedules';
// fetch(backendEndpoint)
// .then(response => response.json())
// .then(data => {
// // 성공 시 처리
// console.log(data);
// const backendDataArray = data.schedules;
// setScheduleData(fetchedData);
// .catch(error => {
// console.error(error);
// });
const backendDataArray =
[{
"id":23423,
"date":"2023-11-19",
"startTime":"10:00",
"endTime":"11:30",
"title":"뇨끼 먹기",
"color":"#8393BE",
"Description":"맛있게 먹기"
},{
"id":1923,
"date":"2023-11-23",
"startTime":"17:00",
"endTime":"19:00",
"title":"까르보나라 만들기",
"color":"#8393BE"
},{
"id":777,
"date":"2023-11-24",
"startTime":"09:00",
"endTime":"12:00",
"title":"강의 듣기",
"color":"#8393BE"
}];
// 만약 backendDataArray가 undefined인지 확인
// 받아온 여러 개의 데이터를 가공하여 사용할 형식으로 변환
const processedDataArray = [];
for (const backendData of backendDataArray) {
// 백엔드에서 받아온 데이터의 날짜 정보를 사용하여 Date 객체 생성
const startDate = new Date(backendData.date);
// "14:00" 형식의 문자열을 받아 현재 날짜에 추가
const startTimeParts = backendData.startTime.split(':');
const endTimeParts = backendData.endTime.split(':');
const startTime = new Date(startDate);
const endTime=new Date(startDate);
const clr=backendData.color;
startTime.setHours(parseInt(startTimeParts[0], 10));
startTime.setMinutes(parseInt(startTimeParts[1], 10));
endTime.setHours(parseInt(endTimeParts[0], 10));
endTime.setMinutes(parseInt(endTimeParts[1], 10));
processedDataArray.push({
id: backendData.id,
date: backendData.date,
start:startTime,
end: endTime,
title: backendData.title,
color:clr,
description: backendData.Description
});
}
// 변환된 데이터 배열을 JSON 문자열로 변환
// JSON 문자열을 상태에 설정
setScheduleData(processedDataArray);
// 초기 데이터를 스케줄 데이터에 설정
//setScheduleData(initialData);
// })
}, []);
const handleDeleteEvent=(id, deleteOption)=>{
let deleteUrl = `/scheduler/${id}`;
const deleteData= {
afterDay: deleteOption==='afterDay',
total: deleteOption==='total',
}
fetch(deleteUrl,{
method: 'DELETE',
headers:{
'Content-Type':'application/json',
},
body: JSON.stringify(deleteData)
})
.then(response => response.json())
.then(data => {
// 성공 시 처리
console.log(data);
})
.catch(error => {
// 실패 시 처리
console.error(error);
});
};
const kEventElements = document.querySelectorAll(".k-event");
const handleScheduleClick = (event) => {
console.log('Item clicked:', event.target);
setSelectedSchedule(event);
setIsDeModalOpen(true);
//console.log('클릭시 isDeModalOpen:', isDeModalOpen);
};
useEffect(() => {
console.log('클릭시 isDeModalOpen:', isDeModalOpen);
}, [isDeModalOpen]);
// 각 요소에 새로운 클릭 이벤트 리스너 등록
kEventElements.forEach((element) => {
element.addEventListener('click', handleScheduleClick);
});
/*
useEffect(() => {
// 페이지가 로드될 때 실행되는 코드
const initialScheduleElement = document.querySelector(".k-event");
const handleInitialScheduleClick = (event) => {
setSelectedSchedule(event.target);
setIsDeModalOpen(true);
};
if (initialScheduleElement) {
initialScheduleElement.addEventListener('click', handleInitialScheduleClick);
}
// 컴포넌트가 언마운트될 때 이벤트 리스너를 정리합니다.
return () => {
if (initialScheduleElement) {
initialScheduleElement.removeEventListener('click', handleInitialScheduleClick);
}
}
}, [setSelectedSchedule, setIsDeModalOpen]); // 의존성 배열에 명시
// ... (기타 코드)
// 빈 배열을 전달하여 한 번만 실행되도록 합니다.
*/
return (
<div>
<div className={main_styles.main_header}>
<Header />
</div>
<div className={main_styles.scheduler_container}>
<div className={main_styles.side_container}>
<h1>side부분</h1>
</div>
<div className={main_styles.scheduler_content}>
<div className={main_styles.button_handler}>
<button className={main_styles.add_event_button} onClick={openModal}>
일정추가
</button>
<button className={main_styles.inquiry_event_button} onClick={openInModal}>
일정조회
</button>
</div>
<div>
<Scheduler data={scheduleData}>
<WeekView
startDate={selectedDate}
eventRender={(event) => (
<div
style={{
backgroundColor: event.dataItem.color || '#8393BE',
// 다른 스타일링 속성을 원하는 경우 여기에 추가하세요.
}}
>
{event.dataItem.title}
</div>
)}
/>
<DayView startDate={selectedDate}/>
<MonthView />
</Scheduler>
</div>
<ScheduleAddModal
isOpen={isModalOpen}
onClose={closeModal}
onSave={handleSaveEvent}
/>
<ScheduleDeleteModal
isOpen={isDeModalOpen}
onClose={closeDeModal}
onDelete={handleDeleteEvent}
schedule={selectedSchedule}
/>
<ScheduleInquiryModal
isOpen={isInModalOpen}
onClose={closeInModal}
onInquiry={handleInquiryEvent}
/>
</div>
</div>
</div>
);
};
export default MySchedulerApp;
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment