Код: Выделить всё
import Day from "./Day";
import style from "./Calendar.module.css";
import { useState } from "react";
import type { DayInScope } from "./types";
export default function Calendar() {
const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear();
const [selectedMonth, setSelectedMonth] = useState(currentMonth);
const [selectedYear, setSelectedYear] = useState(currentYear);
// Helper functions
function daysInMonth(monthIndex: number, year: number): DayInScope[] {
const daysCount = new Date(year, monthIndex + 1, 0).getDate();
const days: DayInScope[] = [];
for (let day = 1; day {
return (new Date(year, monthIndex + 1, 0).getDay() + 6) % 7; // Adjusting so that Monday=0, Sunday=6
};
function setMonthLeft() {
console.log("left");
setSelectedMonth((prevMonth) => {
if (prevMonth === 0) {
setSelectedYear((prevYear) => {
console.log(
"prevmonth was 0, setting month to 11 and changing year from" +
selectedYear +
" to " +
(selectedYear - 1)
);
return prevYear - 1;
});
return 11;
} else {
console.log(
"decreasing month from " + prevMonth + " to " + (prevMonth - 1)
);
return prevMonth - 1;
}
});
}
function setMonthRight() {
console.log("right");
setSelectedMonth((prevMonth) => {
if (prevMonth === 11) {
setSelectedYear((prevYear) => {
console.log(
"prevmonth was 11, setting month to 0 and changing year from" +
selectedYear +
" to " +
(selectedYear + 1)
);
return prevYear + 1;
});
return 0;
} else {
console.log(
"increasing month from " + prevMonth + " to " + (prevMonth + 1)
);
return prevMonth + 1;
}
});
}
// Full scope
const fullScope: DayInScope[] = daysInMonth(selectedMonth, selectedYear);
// Days before
const firstDay = firstDayWeekPos(selectedMonth, selectedYear);
const daysBefore: DayInScope[] = [];
if (firstDay !== 0) {
const prevMonth = selectedMonth === 0 ? 11 : selectedMonth - 1;
const prevMonthYear = selectedMonth === 0 ? selectedYear - 1 : selectedYear;
// if not monday
const prevMonthDays = daysInMonth(prevMonth, prevMonthYear);
for (let i = firstDay - 1; i >= 0; i--) {
daysBefore.push(prevMonthDays[prevMonthDays.length - 1 - i]);
}
}
fullScope.unshift(...daysBefore);
// Days after
const daysAfter: DayInScope[] = [];
const lastDay = lastDayWeekPos(selectedMonth, selectedYear);
if (lastDay !== 6) {
//if last day not sunday
const daysToAdd = 6 - lastDay;
const nextMonth = selectedMonth === 11 ? 0 : selectedMonth + 1;
const nextMonthYear =
selectedMonth === 11 ? selectedYear + 1 : selectedYear;
for (let i = 1; i {
return (
);
})}
);
}
Я также хотел бы знать, есть ли в коде какие-либо серьезные конструктивные недостатки. заранее спасибо
Подробнее здесь: https://stackoverflow.com/questions/798 ... me-details
Мобильная версия