Skip to content

Commit

Permalink
Refactor/139 미래 일기 못하게 변경, 새로고침시 현재 날짜 안바뀌게 수정 (#150)
Browse files Browse the repository at this point in the history
* [refactor] 캘린더에서 달 이동시 1일로 고정되게 변경

* [feat] 캘린더 날짜 선택시 쿼리스트링으로 날짜 데이터를 저장하여 새로고침시 날짜가 변경되지 않게 변경

ˆ

* [refactor] 이후 날짜 클릭 안되게 수정

* [fix] 이후 달 선택 못하게 변경

[fix] 이후 달 선택 못하게 변경

[fix] 이후 달 선택 못하게 변경

* [fix] 일기가 있을때 표시되는 Dot 컴포넌트 2px 올림
  • Loading branch information
Leewonchan14 authored Aug 11, 2024
1 parent d903857 commit e6ce446
Show file tree
Hide file tree
Showing 10 changed files with 94 additions and 69 deletions.
29 changes: 29 additions & 0 deletions src/components/calendar/Calendar.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
import { CalendarMonthSelector } from "./CalendarMonthSelector";
import { CalendarGrid } from "./CalendarGrid";
import { useCalendarStore } from "../../stores/CalendarStore";
import { useEffect } from "react";
import { useSearchParams } from "react-router-dom";

export const Calendar = () => {
const [searchParams, setQuery] = useSearchParams();
const query = Object.fromEntries(searchParams.entries());
const { selectedDate, setSelectedDate } = useCalendarStore((state) => state);

// 초기 선택된 날짜가 쿼리로 들어왔을 때
useEffect(() => {
const { year, month, day } = query;
if (!year || !month || !day) return;

setSelectedDate({
year: parseInt(year),
month: parseInt(month),
day: parseInt(day),
});
}, []);

// 날짜를 선택 할때 마다 쿼리를 변경
useEffect(() => {
setQuery(
{ ...selectedDate },
{
replace: true,
}
);
}, [selectedDate]);

return (
<>
<CalendarMonthSelector />
Expand Down
37 changes: 20 additions & 17 deletions src/components/calendar/CalendarGrid.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
CALENDAR_HEADER,
getCalendarDaysInMonth,
getNow,
isEqualDate,
isSaturday,
isSunday,
Expand Down Expand Up @@ -28,26 +29,30 @@ const CalendarHeader = () => {
};

const CalenderBody = () => {
let { setSelectedDate, selectedYearMonth } = useCalendarStore(
(state) => state
);
let { setSelectedDate, selectedDate } = useCalendarStore((state) => state);

// 선택된 달의 길이가 42인 날짜 배열 => ["", "" ,1 , 2, ... , "" ]
const days = getCalendarDaysInMonth({ ...selectedYearMonth });
const days = getCalendarDaysInMonth({ ...selectedDate });

const handleClickCell = (day) => {
if (!day) return;

setSelectedDate({
...selectedYearMonth,
...selectedDate,
day,
});
};

const isCanWriteDiaryDay = (day) => {
const { year, month } = selectedDate;
const { year: nowYear, month: nowMonth, day: nowDay } = getNow();
return !(year >= nowYear && month >= nowMonth && day > nowDay);
};

return days.map((day, index) => (
<CalendarBodyCell
key={dateToDashString({ ...selectedYearMonth, day: index })}
{...{ day, handleClickCell }}
key={dateToDashString({ ...selectedDate, day: index })}
{...{ day, handleClickCell, isCanWrite: isCanWriteDiaryDay(day) }}
/>
));
};
Expand All @@ -68,31 +73,30 @@ const CalendarHeaderCell = ({ index, day, className }) => {
);
};

const CalendarBodyCell = ({ handleClickCell, day, index }) => {
let { selectedDate, selectedYearMonth } = useCalendarStore((state) => state); // 선택된 달의 길이가 42인 날짜 배열 => ["", "" ,1 , 2, ... , "" ]
const CalendarBodyCell = ({ handleClickCell, day, index, isCanWrite }) => {
let { selectedDate } = useCalendarStore((state) => state); // 선택된 달의 길이가 42인 날짜 배열 => ["", "" ,1 , 2, ... , "" ]

let { isCanRender, isDiaryExistDay } = useFetchDiaryChecks();

const isSelectedCell = (day) => {
return isEqualDate(selectedDate, {
...selectedYearMonth,
...selectedDate,
day,
});
};

return (
<div className={`flex justify-center items-center w-full`}>
<div className={`flex justify-center items-center w-full ${!isCanWrite && "text-gray-300"}`}>
<div
onClick={() => isCanWrite && handleClickCell(day)}
className={
"relative flex justify-center w-16 h-16 mobile:w-10 mobile:h-10"
}
>
{!isCanRender && <ResponseSkeleton />}
{isCanRender && (
<>
<CellWithCircle
{...{ isSelectedCell, index, day, handleClickCell }}
/>
<CellWithCircle {...{ isSelectedCell, index, day }} />
<Dot
isVisible={isDiaryExistDay(day)}
isSelected={isSelectedCell(day)}
Expand All @@ -104,10 +108,9 @@ const CalendarBodyCell = ({ handleClickCell, day, index }) => {
);
};

const CellWithCircle = ({ day, index, isSelectedCell, handleClickCell }) => {
const CellWithCircle = ({ day, index, isSelectedCell }) => {
return (
<div
onClick={() => handleClickCell(day)}
className={`flex flex-col justify-center aspect-square items-center rounded-full cursor-pointer px-1
${isSunday(index) && "text-red-600"}
${isSaturday(index) && "text-blue-600"}
Expand All @@ -122,7 +125,7 @@ const CellWithCircle = ({ day, index, isSelectedCell, handleClickCell }) => {
const Dot = ({ isVisible, isSelected }) => {
return (
<span
className={`absolute bottom-0 w-2 h-2 bg-primary-600 rounded-full invisible ${isVisible && "!visible"} ${isSelected && "!bg-white"}`}
className={`absolute bottom-[2px] w-2 h-2 bg-primary-600 rounded-full invisible ${isVisible && "!visible"} ${isSelected && "!bg-white"}`}
/>
);
};
27 changes: 19 additions & 8 deletions src/components/calendar/CalendarMonthSelector.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";
import { getNextYearMonth, getPreYearMonth } from "../../utils/calendar/date";
import {
getNextYearMonth,
getNow,
getPreYearMonth,
} from "../../utils/calendar/date";
import { useCalendarStore } from "../../stores/CalendarStore";
import { yearMonthToKoreanString } from "../../utils/api/dateConverter";

export const CalendarMonthSelector = () => {
let { selectedYearMonth, setSelectedYearMonth } = useCalendarStore(
(state) => state
);
let { selectedDate, setSelectedDate } = useCalendarStore((state) => state);

const { year: nextYear, month: nextMonth } = getNextYearMonth(selectedDate);
const { year: nowYear, month: nowMonth } = getNow();
const isCanGoNextMonth =
nextYear < nowYear || (nextYear === nowYear && nextMonth <= nowMonth);

const goPreMonth = () => {
setSelectedYearMonth(getPreYearMonth(selectedYearMonth));
setSelectedDate({ ...getPreYearMonth(selectedDate), day: 1 });
};

const goNextMonth = () => {
setSelectedYearMonth(getNextYearMonth(selectedYearMonth));
if (!isCanGoNextMonth) return;

const { year: nextYear, month: nextMonth } = getNextYearMonth(selectedDate);

setSelectedDate({ year: nextYear, month: nextMonth, day: 1 });
};

return (
Expand All @@ -32,11 +43,11 @@ export const CalendarMonthSelector = () => {
"font-bold flex justify-center items-center text-nowrap w-0"
}
>
{yearMonthToKoreanString(selectedYearMonth)}
{yearMonthToKoreanString(selectedDate)}
</span>
<IoIosArrowForward
size={50}
className={"cursor-pointer"}
className={`cursor-pointer ${isCanGoNextMonth ? "" : "invisible"}`}
onClick={goNextMonth}
/>
</div>
Expand Down
13 changes: 7 additions & 6 deletions src/hooks/diary/queries/useFetchDiaryChecks.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,20 @@ import useRequireAuth from "../../auth/useRequireAuth";
* }}
*/
const useFetchDiaryChecks = () => {
let { selectedDate, selectedYearMonth } = useCalendarStore((state) => state);
let { selectedDate } = useCalendarStore((state) => state);
const { year, month } = selectedDate;
const { userId, isLogin } = useRequireAuth();
let {
isFetching,
isSuccess,
data: diaryChecks,
} = useQuery({
queryKey: diaryCheckQueryKey(selectedYearMonth),
queryKey: diaryCheckQueryKey({ year, month }),
queryFn: async () => {
const response = await DiaryController.findCheckDiaries({
userId,
...selectedYearMonth,
year,
month,
});
return response.data.result;
},
Expand All @@ -36,7 +38,7 @@ const useFetchDiaryChecks = () => {
const isCanRender = !isFetching && isSuccess;

const isDiaryExistDay = (day) => {
return diaryChecks?.[yearMonthToDashString({ ...selectedYearMonth })]?.[day]
return diaryChecks?.[yearMonthToDashString({ year, month })]?.[day]
?.isExist;
};

Expand All @@ -51,8 +53,7 @@ const useFetchDiaryChecks = () => {
};
};

export const diaryCheckQueryKey = (selectedYearMonth) => {
const { year, month } = selectedYearMonth;
export const diaryCheckQueryKey = ({ year, month }) => {
return ["diary", year, month];
};

Expand Down
20 changes: 7 additions & 13 deletions src/hooks/diaryDetail/queries/useCreateDiary.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { delay } from "../../../utils/api/delay";
import { diaryCheckQueryKey } from "../../diary/queries/useFetchDiaryChecks";
import {
dateToDashString,
Expand All @@ -15,9 +14,7 @@ import DiaryController from "../../../apis/diary.controller";
import useRequireAuth from "../../auth/useRequireAuth";

const useCreateDiary = () => {
const { selectedDate, selectedYearMonth } = useCalendarStore(
(state) => state
);
const { selectedDate } = useCalendarStore((state) => state);

const { userId } = useRequireAuth();
let queryClient = useQueryClient();
Expand All @@ -32,15 +29,12 @@ const useCreateDiary = () => {
});
},
onMutate: async (content) => {
queryClient.setQueryData(
diaryCheckQueryKey(selectedYearMonth),
(old) => ({
[yearMonthToDashString(selectedYearMonth)]: {
...old[yearMonthToDashString(selectedYearMonth)],
[selectedDate.day]: { isExist: true },
},
})
);
queryClient.setQueryData(diaryCheckQueryKey(selectedDate), (old) => ({
[yearMonthToDashString(selectedDate)]: {
...old[yearMonthToDashString(selectedDate)],
[selectedDate.day]: { isExist: true },
},
}));

queryClient.setQueryData(diaryQueryKey(selectedDate), (old) => ({
...old,
Expand Down
20 changes: 7 additions & 13 deletions src/hooks/diaryDetail/queries/useUpdateDiary.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
import { delay } from "../../../utils/api/delay";
import DiaryController from "../../../apis/diary.controller";
import { yearMonthToDashString } from "../../../utils/api/dateConverter";
import { diaryCheckQueryKey } from "../../diary/queries/useFetchDiaryChecks";
Expand All @@ -14,9 +13,7 @@ import useFetchDiary, {
import useRequireAuth from "../../auth/useRequireAuth";

const useUpdateDiary = () => {
const { selectedDate, selectedYearMonth } = useCalendarStore(
(state) => state
);
const { selectedDate } = useCalendarStore((state) => state);

let queryClient = useQueryClient();

Expand All @@ -33,15 +30,12 @@ const useUpdateDiary = () => {
});
},
onMutate: async (content) => {
queryClient.setQueryData(
diaryCheckQueryKey(selectedYearMonth),
(old) => ({
[yearMonthToDashString(selectedYearMonth)]: {
...old[yearMonthToDashString(selectedYearMonth)],
[selectedDate.day]: { isExist: true },
},
})
);
queryClient.setQueryData(diaryCheckQueryKey(selectedDate), (old) => ({
[yearMonthToDashString(selectedDate)]: {
...old[yearMonthToDashString(selectedDate)],
[selectedDate.day]: { isExist: true },
},
}));

queryClient.setQueryData(diaryQueryKey(selectedDate), (old) => ({
...old,
Expand Down
4 changes: 2 additions & 2 deletions src/pages/diarys/Diary.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const Diary = () => {
};

const useBottomSheetPosition = () => {
let { selectedDate, selectedYearMonth } = useCalendarStore((state) => state);
let { selectedDate } = useCalendarStore((state) => state);

const [position, setPosition] = useState(BOTTOM_POSITION);

Expand All @@ -47,7 +47,7 @@ const useBottomSheetPosition = () => {
// 달이 변경되면 BottomSheet 의 위치를 초기화
useEffect(() => {
setPosition(BOTTOM_POSITION);
}, [selectedYearMonth]);
}, [selectedDate.month]);

return { position, setPosition, isDiaryExistDay };
};
Expand Down
3 changes: 1 addition & 2 deletions src/pages/mypage/RecentDiaries.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const MonthlyTitle = ({ year, month }) => {
};

const DiaryItem = ({ diary }) => {
const { setSelectedYearMonth, setSelectedDate } = useCalendarStore(
const { setSelectedDate } = useCalendarStore(
(state) => state
);

Expand All @@ -65,7 +65,6 @@ const DiaryItem = ({ diary }) => {
const [year, month, day] = createDate.split("-").map((i) => Number(i));

const onClick = () => {
setSelectedYearMonth({ year, month });
setSelectedDate({ year, month, day });
navigate(DIARY_PAGE_PATH);
};
Expand Down
7 changes: 0 additions & 7 deletions src/stores/CalendarStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,10 @@ const { year, month, day } = getNow();

export const useCalendarStore = create((set) => ({
selectedDate: { year, month, day },
selectedYearMonth: { year, month },

setSelectedDate: ({ year, month, day }) => {
set((state) => ({
selectedDate: { year, month, day },
}));
},

setSelectedYearMonth: ({ year, month }) => {
set((state) => ({
selectedYearMonth: { year, month },
}));
},
}));
3 changes: 2 additions & 1 deletion src/utils/calendar/date.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { range } from "../array/range";

export const CALENDAR_HEADER = ["일", "월", "화", "수", "목", "금", "토"];

const now = new Date();

export const getNow = () => {
const now = new Date();
return {
year: now.getFullYear(),
month: now.getMonth() + 1,
Expand Down

0 comments on commit e6ce446

Please sign in to comment.