Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FE-27 🔧 마이페이지 누락 수정 #243

Merged
merged 4 commits into from
Aug 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions src/user/ui-calendar/Calendar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React, { useState } from 'react';
import Image from 'next/image';
import { subMonths } from 'date-fns';
import { EmotionLog, EmotionTypeEN } from '@/types/emotion';
import useCalendar from '../../hooks/useCalendar';
import { DAY_LIST, DATE_MONTH_FIXER, iconPaths } from '../utill/constants';
import CalendarHeader from './CalendarHeader';

interface CalendarProps {
currentDate: Date; // 현재 날짜
setCurrentDate: React.Dispatch<React.SetStateAction<Date>>; // 현재 날짜를 설정하는 함수
monthlyEmotionLogs: EmotionLog[];
}

export default function Calendar({ currentDate, setCurrentDate, monthlyEmotionLogs }: CalendarProps) {
// 캘린더 함수 호출
const { weekCalendarList } = useCalendar(currentDate);
// 감정 필터
const [selectedEmotion, setSelectedEmotion] = useState<EmotionTypeEN | null>(null);

// 달력에 출력할 수 있게 매핑
const emotionMap: Record<string, EmotionTypeEN> = Array.isArray(monthlyEmotionLogs)
? monthlyEmotionLogs.reduce<Record<string, EmotionTypeEN>>((acc, log) => {
const date = new Date(log.createdAt);
const dateString = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
acc[dateString] = log.emotion as EmotionTypeEN;
return acc;
}, {})
: {};

// 이전 달 클릭
const handlePrevMonth = () => setCurrentDate((prevDate) => subMonths(prevDate, DATE_MONTH_FIXER));
// 다음 달 클릭
const handleNextMonth = () => setCurrentDate((prevDate) => subMonths(prevDate, -DATE_MONTH_FIXER));

// 감정 필터
const handleEmotionSelect = (emotion: EmotionTypeEN) => {
// 현재 선택된 감정과 같으면 초기화
if (selectedEmotion === emotion) {
setSelectedEmotion(null);
} else {
setSelectedEmotion(emotion);
}
};

// 필터링된 감정 맵 생성
const filteredEmotionMap = selectedEmotion ? Object.fromEntries(Object.entries(emotionMap).filter(([, value]) => value === selectedEmotion)) : emotionMap;

return (
<div className='flex flex-col w-full lg:max-w-[640px] md:max-w-[640px] mt-[160px] space-y-0 md:mb-10 mb-5 gap-[48px]'>
{/* 캘린더 헤더 */}
<CalendarHeader currentDate={currentDate} onPrevMonth={handlePrevMonth} onNextMonth={handleNextMonth} onEmotionSelect={handleEmotionSelect} selectEmotion={selectedEmotion} />
{/* 캘린더 */}
<div>
<div className='flex'>
{DAY_LIST.map((day) => (
<div key={day} className='w-[91px] h-[91px] border-t border-b border-gray-100 text-stone-300 font-semibold text-2xl flex items-center justify-center'>
{day}
</div>
))}
</div>
{weekCalendarList.map((week, weekIndex) => (
// TODO: index 값 Lint error. 임시로 주석 사용. 추후 수정 예정
// eslint-disable-next-line react/no-array-index-key
<div key={weekIndex} className='flex'>
{week.map((day, dayIndex) => {
// 현재 날짜와 비교
const isToday = day === currentDate.getDate() && currentDate.getMonth() === new Date().getMonth() && currentDate.getFullYear() === new Date().getFullYear();
const dateString = `${currentDate.getFullYear()}-${String(currentDate.getMonth() + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
const emotion: EmotionTypeEN = filteredEmotionMap[dateString]; // 날짜에 해당하는 감정 가져오기
const iconPath = emotion && iconPaths[emotion] ? iconPaths[emotion].path : '/icon/BW/SmileFaceBWIcon.svg';

return (
<div
// TODO: index 값 Lint error. 임시로 주석 사용. 추후 수정 예정
// eslint-disable-next-line react/no-array-index-key
key={dayIndex}
className={`w-[91px] h-[91px] font-semibold flex items-center justify-center ${isToday ? 'border-4 border-red-400 text-red-400 rounded-[3px]' : 'border-b border-gray-100 text-stone-300'}`}
>
{emotion ? (
<div className='flex flex-col justify-center items-center gap-2'>
<p>{day}</p>
<Image src={iconPath} alt='감정' width={36} height={36} />
</div>
) : (
<p className='text-2xl'>{day}</p>
)}
</div>
);
})}
</div>
))}
</div>
</div>
);
}
58 changes: 58 additions & 0 deletions src/user/ui-calendar/CalendarHeader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuGroup, DropdownMenu } from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import Image from 'next/image';
import { EmotionTypeEN } from '@/types/emotion';
import ARROW_BOTTOM_ICON from '../../../public/icon/arrow-bottom-icon.svg';
import ARROW_RIGHT_ICON from '../../../public/icon/arrow-right-icon.svg';
import ARROW_LEFT_ICON from '../../../public/icon/arrow-left-icon.svg';
import { iconPaths } from '../utill/constants';

interface CalendarHeaderProps {
currentDate: Date;
onPrevMonth: () => void;
onNextMonth: () => void;
onEmotionSelect: (emotion: EmotionTypeEN) => void;
selectEmotion: EmotionTypeEN | null;
}

export default function CalendarHeader({ currentDate, onPrevMonth, onNextMonth, onEmotionSelect, selectEmotion }: CalendarHeaderProps) {
return (
<div className='w-full flex justify-between items-center'>
<div className='flex w-full h-[52px] justify-between items-center'>
<div className='text-neutral-700 text-2xl font-semibold leading-loose'>{`${currentDate.getFullYear()}년 ${currentDate.getMonth() + 1}월`}</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant='outline' className='flex items-center gap-1 bg-slate-100 rounded-[14px] text-center text-stone-300 text-xl'>
필터: 감동
<div className='w-9 h-9 relative'>
<Image src={ARROW_BOTTOM_ICON} alt='필터 선택' width={36} height={36} />
</div>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className='bg-white'>
<DropdownMenuGroup className='flex flex-row'>
{Object.entries(iconPaths).map(([emotionKey, { path, name }]) => (
<DropdownMenuItem key={emotionKey}>
<Button
className={`p-0 w-14 h-14 bg-opacity-20 rounded-2xl flex justify-center ${selectEmotion === emotionKey ? 'border-4 border-illust-yellow' : ''}`}
onClick={() => onEmotionSelect(emotionKey as EmotionTypeEN)}
>
<Image src={path} alt={name} width={36} height={36} />
</Button>
</DropdownMenuItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className='flex gap-6'>
<Button variant='default' className='p-0' onClick={onPrevMonth}>
<Image src={ARROW_LEFT_ICON} alt='이전' width={36} height={36} />
</Button>
<Button variant='default' className='p-0' onClick={onNextMonth}>
<Image src={ARROW_RIGHT_ICON} alt='다음' width={36} height={36} />
</Button>
</div>
</div>
);
}
96 changes: 96 additions & 0 deletions src/user/ui-chart/Chart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { EmotionLog, EmotionTypeEN } from '@/types/emotion';
import Image from 'next/image';
import { iconPaths } from '../utill/constants';

interface ChartProps {
monthlyEmotionLogs: EmotionLog[];
}

export default function Chart({ monthlyEmotionLogs }: ChartProps) {
// 감정별 빈도수 계산
const emotionCounts = monthlyEmotionLogs.reduce(
(count, log) => {
const { emotion } = log;
return {
...count, // 기존의 count를 복사
[emotion]: (count[emotion] || 0) + 1, // 현재 감정의 개수 증가
};
},
{} as Record<string, number>,
);

// 감정 종류 및 총 감정 수 계산
const TOTAL_COUNT = monthlyEmotionLogs.length;
const EMOTIONS: EmotionTypeEN[] = ['MOVED', 'HAPPY', 'WORRIED', 'SAD', 'ANGRY'];
const RADIUS = 90; // 원의 반지름
const CIRCUMFERENCE = 2 * Math.PI * RADIUS;

// 가장 많이 나타나는 감정 찾기
const maxEmotion = EMOTIONS.reduce((max, emotion) => (emotionCounts[emotion] > emotionCounts[max] ? emotion : max), EMOTIONS[0]);

// 원형 차트의 각 감정에 대한 strokeDasharray와 strokeDashoffset 계산
let offset = 0;

return (
<div className='flex flex-col w-full lg:max-w-[640px] md:max-w-[640px] mt-[160px] space-y-0 md:mb-10 mb-5 gap-[48px]'>
<h2 className='text-neutral-700 text-2xl font-semibold leading-loose'>감정 차트</h2>
<div className='flex justify-between items-center px-[112px]'>
<div className='w-[200px] h-[200px] relative'>
<svg viewBox='0 0 200 200'>
<circle cx='100' cy='100' r={RADIUS} fill='none' stroke='beige' strokeWidth='20' />
{EMOTIONS.map((emotion) => {
const count = emotionCounts[emotion] || 0;
const percentage = TOTAL_COUNT > 0 ? count / TOTAL_COUNT : 0; // 0으로 나누기 방지
const strokeDasharray = `${CIRCUMFERENCE * percentage} ${CIRCUMFERENCE * (1 - percentage)}`;

// 색상 설정
let strokeColor;
switch (emotion) {
case 'HAPPY':
strokeColor = '#FBC85B';
break;
case 'SAD':
strokeColor = '#E3E9F1';
break;
case 'WORRIED':
strokeColor = '#C7D1E0';
break;
case 'ANGRY':
strokeColor = '#EFF3F8';
break;
default:
strokeColor = '#48BB98';
}

const circle = <circle key={emotion} cx='100' cy='100' r={RADIUS} fill='none' stroke={strokeColor} strokeWidth='20' strokeDasharray={strokeDasharray} strokeDashoffset={offset} />;

offset += CIRCUMFERENCE * percentage; // 다음 원을 위한 offset 업데이트
return circle;
})}
</svg>
{/* 중앙에 가장 많이 나타나는 감정 출력 */}
<div className='absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 flex flex-col items-center gap-3'>
<Image src={iconPaths[maxEmotion].path} alt='감정' width={40} height={40} />
<p>{iconPaths[maxEmotion].name}</p>
</div>
</div>
<div>
<div className='flex flex-col gap-4'>
{EMOTIONS.map((emotion) => {
const count = emotionCounts[emotion] || 0;
const percentage = TOTAL_COUNT > 0 ? Math.floor((count / TOTAL_COUNT) * 100) : 0; // 퍼센트 계산 및 소수점 버리기

return (
<div key={emotion} className='flex items-center gap-3'>
<p className={`${iconPaths[emotion].color} w-[16px] h-[16px]`}></p>
<Image src={iconPaths[emotion].path} alt='감정' width={24} height={24} />
<p>{percentage}%</p>
</div>
);
})}
</div>
</div>
</div>
</div>
);
}
Loading