Files
web/components/TempDesignSystem/Form/Date/index.tsx
2024-11-05 15:47:28 +01:00

215 lines
6.6 KiB
TypeScript

"use client"
import { parseDate } from "@internationalized/date"
import { useState } from "react"
import { DateInput, DatePicker, Group } from "react-aria-components"
import { useController, useFormContext, useWatch } from "react-hook-form"
import { useIntl } from "react-intl"
import { dt } from "@/lib/dt"
import Select from "@/components/TempDesignSystem/Select"
import { rangeArray } from "@/utils/rangeArray"
import ErrorMessage from "../ErrorMessage"
import { DateName } from "./date"
import styles from "./date.module.css"
import type { Key } from "react-aria-components"
import type { DateProps } from "./date"
export default function DateSelect({ name, registerOptions = {} }: DateProps) {
const intl = useIntl()
const currentValue = useWatch({ name })
const { control, setValue, trigger, formState } = useFormContext()
const { field } = useController({
control,
name,
rules: registerOptions,
})
const dayLabel = intl.formatMessage({ id: "Day" })
const monthLabel = intl.formatMessage({ id: "Month" })
const yearLabel = intl.formatMessage({ id: "Year" })
const initialDate = dt(currentValue)
const [selectedYear, setSelectedYear] = useState<number | null>(
initialDate.isValid() ? initialDate.year() : null
)
const [selectedMonth, setSelectedMonth] = useState<number | null>(
initialDate.isValid() ? initialDate.month() : null
)
const [selectedDay, setSelectedDay] = useState<number | null>(
initialDate.isValid() ? initialDate.date() : null
)
const currentYear = new Date().getFullYear()
const months = rangeArray(1, 12).map((month) => ({
value: month,
label: `${month}`,
}))
const years = rangeArray(1900, currentYear - 18)
.reverse()
.map((year) => ({ value: year, label: year.toString() }))
function getDaysInMonth(year: number | null, month: number | null): number {
if (month === null) {
return 31
}
const yearToUse = year ?? new Date().getFullYear()
return dt(`${yearToUse}-${month + 1}-01`).daysInMonth()
}
const days = rangeArray(1, getDaysInMonth(selectedYear, selectedMonth)).map(
(day) => ({
value: day,
label: `${day}`,
})
)
function handleSegmentChange(selector: DateName, value: number) {
let newYear = selectedYear
let newMonth = selectedMonth
let newDay = selectedDay
switch (selector) {
case DateName.year:
newYear = value
setSelectedYear(newYear)
break
/**
* Months are 0 index based and therefore we
* must subtract by 1 to get the selected month
*/
case DateName.month:
newMonth = value - 1
setSelectedMonth(newMonth)
if (selectedDay) {
const maxDays = getDaysInMonth(newYear, newMonth)
if (selectedDay > maxDays) {
newDay = maxDays
setSelectedDay(newDay)
}
}
break
case DateName.date:
newDay = value
setSelectedDay(newDay)
break
}
// Check if all segments are set and update form value.
if (newYear && newMonth !== null && newDay) {
const newDate = dt().year(newYear).month(newMonth).date(newDay)
if (newDate.isValid()) {
setValue(name, newDate.format("YYYY-MM-DD"))
trigger(name)
}
}
}
let dateValue = null
try {
/**
* parseDate throws when its not a valid
* date, but we can't check isNan since
* we recieve the date as "1999-01-01"
*/
dateValue = dt(currentValue).isValid() ? parseDate(currentValue) : null
} catch (error) {
console.warn("Known error for parse date in DateSelect: ", error)
}
return (
<DatePicker
aria-label={intl.formatMessage({ id: "Select date of birth" })}
isRequired={!!registerOptions.required}
name={name}
ref={field.ref}
value={dateValue}
data-testid={name}
>
<Group>
<DateInput className={styles.container}>
{(segment) => {
switch (segment.type) {
case "day":
return (
<div className={styles.day}>
<Select
aria-label={dayLabel}
items={days}
label={dayLabel}
name={DateName.date}
onSelect={(select: Key) =>
handleSegmentChange(DateName.date, Number(select))
}
placeholder="DD"
required
tabIndex={3}
defaultSelectedKey={
segment.isPlaceholder ? undefined : segment.value
}
value={segment.isPlaceholder ? undefined : segment.value}
/>
</div>
)
case "month":
return (
<div className={styles.month}>
<Select
aria-label={monthLabel}
items={months}
label={monthLabel}
name={DateName.month}
onSelect={(select: Key) =>
handleSegmentChange(DateName.month, Number(select))
}
placeholder="MM"
required
tabIndex={2}
defaultSelectedKey={
segment.isPlaceholder ? undefined : segment.value
}
value={segment.isPlaceholder ? undefined : segment.value}
/>
</div>
)
case "year":
return (
<div className={styles.year}>
<Select
aria-label={yearLabel}
items={years}
label={yearLabel}
name={DateName.year}
onSelect={(select: Key) =>
handleSegmentChange(DateName.year, Number(select))
}
placeholder="YYYY"
required
tabIndex={1}
defaultSelectedKey={
segment.isPlaceholder ? undefined : segment.value
}
value={segment.isPlaceholder ? undefined : segment.value}
/>
</div>
)
default:
/** DateInput forces return of ReactElement */
return <></>
}
}}
</DateInput>
</Group>
<ErrorMessage errors={formState.errors} name={field.name} />
</DatePicker>
)
}