diff --git a/src/components/Stats.jsx b/src/components/Stats.jsx index 54e4476..44f9a4b 100644 --- a/src/components/Stats.jsx +++ b/src/components/Stats.jsx @@ -1,3 +1,42 @@ -const Stats = () =>
STATS
+import { useEffect } from 'react' +import { useLocation } from 'wouter' + +import Button from '@components/Button' +import Calendar from '@components/Calendar' +import { LeftIcon, RightIcon } from '@components/icons' +import Loading from '@components/Loading' +import { ROUTE_MAIN } from '@constants/routes' +import { useFirebase } from '@contexts/FirebaseContext' +import useCalendar from '@hooks/useCalendar' + +import styles from '@styles/components/Stats.module.css' + +const Stats = () => { + const [, setLocation] = useLocation() + const { isLoading, user } = useFirebase() + const { data, days, firstDayOfWeek, monthTitle, nextMonth, prevMonth } = useCalendar() + + useEffect(() => { + if (!isLoading && !user) setLocation(ROUTE_MAIN) + }, [isLoading, user, setLocation]) + + if (isLoading || !data) return + + return ( + <> +
+ + + +
+
+ +
+
+ +
+ + ) +} export default Stats diff --git a/src/hooks/useCalendar.js b/src/hooks/useCalendar.js new file mode 100644 index 0000000..5163132 --- /dev/null +++ b/src/hooks/useCalendar.js @@ -0,0 +1,58 @@ +import { useEffect, useState } from 'react' + +import { useFirebase } from '@contexts/FirebaseContext' + +const twoDigits = (number) => ('0' + number).slice(-2) + +const useCalendar = () => { + const { getAttempts, user } = useFirebase() + const [data, setData] = useState(null) + const [year, setYear] = useState(() => new Date().getFullYear()) + const [month, setMonth] = useState(() => new Date().getMonth() + 1) + + const lastDay = new Date(year, month, 0).getDate() + const firstDayOfWeek = new Date(year, month - 1, 1).getDay() || 7 + + const monthTitle = `${month}/${year}` + const days = [...Array(lastDay).keys()].map(day => + `${year}-${twoDigits(month)}-${twoDigits(day + 1)}` + ) + + const prevMonth = () => { + if (month === 1) { + setMonth(12) + setYear(year - 1) + } else { + setMonth(month - 1) + } + setData(null) + } + + const nextMonth = () => { + if (month === 12) { + setMonth(1) + setYear(year + 1) + } else { + setMonth(month + 1) + } + setData(null) + } + + useEffect(() => { + if (!user) return + const initDate = new Date(year, month - 1) + const finishDate = new Date(year, month, 0) + getAttempts(initDate, finishDate).then(data => setData(data)) + }, [getAttempts, month, year, user]) + + return { + data, + days, + firstDayOfWeek, + monthTitle, + nextMonth, + prevMonth + } +} + +export default useCalendar diff --git a/src/styles/components/Stats.module.css b/src/styles/components/Stats.module.css new file mode 100644 index 0000000..4b798f6 --- /dev/null +++ b/src/styles/components/Stats.module.css @@ -0,0 +1,13 @@ +.header { + display: flex; + flex-direction: row; +} + +.main { + flex-grow: 1; +} + +.footer { + display: flex; + flex-direction: row; +}