fix(SW-360): available days in month

This commit is contained in:
Chuma McPhoy
2024-10-10 08:29:40 +02:00
parent e3df8ea64f
commit ac8f64994f

View File

@@ -32,10 +32,12 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) {
year: number | null year: number | null
month: number | null month: number | null
date: number | null date: number | null
daysInMonth: number
}>({ }>({
year: null, year: null,
month: null, month: null,
date: null, date: null,
daysInMonth: 31,
}) })
const currentYear = new Date().getFullYear() const currentYear = new Date().getFullYear()
@@ -57,12 +59,24 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) {
selector === DateName.month ? Number(select) - 1 : Number(select) selector === DateName.month ? Number(select) - 1 : Number(select)
const newSegments = { ...dateSegments, [selector]: value } const newSegments = { ...dateSegments, [selector]: value }
/**
* Update daysInMonth when year or month changes
* to ensure the user can't select a date that doesn't exist.
*/
if (selector === DateName.year || selector === DateName.month) {
const year = selector === DateName.year ? value : newSegments.year
const month = selector === DateName.month ? value : newSegments.month
if (year !== null && month !== null) {
newSegments.daysInMonth = dt().year(year).month(month).daysInMonth()
}
}
if (Object.values(newSegments).every((val) => val !== null)) { if (Object.values(newSegments).every((val) => val !== null)) {
const newDate = dt() const newDate = dt()
.utc() .utc()
.set("year", newSegments.year!) .set("year", newSegments.year!)
.set("month", newSegments.month!) .set("month", newSegments.month!)
.set("date", newSegments.date!) .set("date", Math.min(newSegments.date!, newSegments.daysInMonth))
setValue(name, newDate.format("YYYY-MM-DD")) setValue(name, newDate.format("YYYY-MM-DD"))
} }
@@ -100,16 +114,11 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) {
{(segment) => { {(segment) => {
switch (segment.type) { switch (segment.type) {
case "day": case "day":
let days = [] const maxDays = dateSegments.daysInMonth
if (segment.maxValue && segment.minValue) { const days = rangeArray(1, maxDays).map((day) => ({
days = rangeArray(segment.minValue, segment.maxValue).map( value: day,
(day) => ({ value: day, label: `${day}` }) label: `${day}`,
) }))
} else {
days = Array.from(Array(segment.maxValue).keys()).map(
(i) => ({ value: i + 1, label: `${i + 1}` })
)
}
return ( return (
<div className={styles.day}> <div className={styles.day}>
<Select <Select