Migrate to a monorepo setup - step 1 * Move web to subfolder /apps/scandic-web * Yarn + transitive deps - Move to yarn - design-system package removed for now since yarn doesn't support the parameter for token (ie project currently broken) - Add missing transitive dependencies as Yarn otherwise prevents these imports - VS Code doesn't pick up TS path aliases unless you open /apps/scandic-web instead of root (will be fixed with monorepo) * Pin framer-motion to temporarily fix typing issue https://github.com/adobe/react-spectrum/issues/7494 * Pin zod to avoid typ error There seems to have been a breaking change in the types returned by zod where error is now returned as undefined instead of missing in the type. We should just handle this but to avoid merge conflicts just pin the dependency for now. * Pin react-intl version Pin version of react-intl to avoid tiny type issue where formatMessage does not accept a generic any more. This will be fixed in a future commit, but to avoid merge conflicts just pin for now. * Pin typescript version Temporarily pin version as newer versions as stricter and results in a type error. Will be fixed in future commit after merge. * Setup workspaces * Add design-system as a monorepo package * Remove unused env var DESIGN_SYSTEM_ACCESS_TOKEN * Fix husky for monorepo setup * Update netlify.toml * Add lint script to root package.json * Add stub readme * Fix react-intl formatMessage types * Test netlify.toml in root * Remove root toml * Update netlify.toml publish path * Remove package-lock.json * Update build for branch/preview builds Approved-by: Linus Flood
217 lines
6.6 KiB
TypeScript
217 lines
6.6 KiB
TypeScript
"use client"
|
|
import { parseDate } from "@internationalized/date"
|
|
import { useEffect } from "react"
|
|
import { DateInput, DatePicker, Group, type Key } 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 useLang from "@/hooks/useLang"
|
|
import { getLocalizedMonthName } from "@/utils/dateFormatting"
|
|
import { rangeArray } from "@/utils/rangeArray"
|
|
|
|
import ErrorMessage from "../ErrorMessage"
|
|
import { DateName, type DateProps } from "./date"
|
|
|
|
import styles from "./date.module.css"
|
|
|
|
export default function DateSelect({ name, registerOptions = {} }: DateProps) {
|
|
const intl = useIntl()
|
|
const lang = useLang()
|
|
|
|
const { control, setValue, formState, watch } = useFormContext()
|
|
const { field, fieldState } = useController({
|
|
control,
|
|
name,
|
|
rules: registerOptions,
|
|
})
|
|
|
|
const currentDateValue = useWatch({ name })
|
|
const year = watch(DateName.year)
|
|
const month = watch(DateName.month)
|
|
const day = watch(DateName.day)
|
|
|
|
const minAgeDate = dt().subtract(18, "year").toDate() // age 18
|
|
const minAgeYear = minAgeDate.getFullYear()
|
|
const minAgeMonth = year === minAgeYear ? minAgeDate.getMonth() + 1 : null
|
|
const minAgeDay =
|
|
Number(year) === minAgeYear && Number(month) === minAgeMonth
|
|
? minAgeDate.getDate()
|
|
: null
|
|
|
|
const months = rangeArray(1, minAgeMonth ?? 12).map((month) => ({
|
|
value: month,
|
|
label: getLocalizedMonthName(month, lang),
|
|
}))
|
|
|
|
const years = rangeArray(1900, minAgeYear)
|
|
.reverse()
|
|
.map((year) => ({ value: year, label: year.toString() }))
|
|
|
|
// Calculate available days based on selected year and month
|
|
const daysInMonth = getDaysInMonth(
|
|
year ? Number(year) : null,
|
|
month ? Number(month) - 1 : null
|
|
)
|
|
|
|
const days = rangeArray(1, minAgeDay ?? daysInMonth).map((day) => ({
|
|
value: day,
|
|
label: `${day}`,
|
|
}))
|
|
|
|
const dayLabel = intl.formatMessage({ id: "Day" })
|
|
const monthLabel = intl.formatMessage({ id: "Month" })
|
|
const yearLabel = intl.formatMessage({ id: "Year" })
|
|
|
|
useEffect(() => {
|
|
if (formState.isSubmitting) return
|
|
|
|
if (month && day) {
|
|
const maxDays = getDaysInMonth(
|
|
year ? Number(year) : null,
|
|
Number(month) - 1
|
|
)
|
|
const adjustedDay = Number(day) > maxDays ? maxDays : Number(day)
|
|
|
|
if (adjustedDay !== Number(day)) {
|
|
setValue(DateName.day, adjustedDay)
|
|
}
|
|
}
|
|
|
|
const newDate = dt()
|
|
.year(Number(year))
|
|
.month(Number(month) - 1)
|
|
.date(Number(day))
|
|
|
|
if (newDate.isValid()) {
|
|
setValue(name, newDate.format("YYYY-MM-DD"), {
|
|
shouldDirty: true,
|
|
shouldTouch: true,
|
|
shouldValidate: true,
|
|
})
|
|
}
|
|
}, [year, month, day, setValue, name, formState.isSubmitting])
|
|
|
|
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(currentDateValue).isValid()
|
|
? parseDate(currentDateValue)
|
|
: null
|
|
} catch (error) {
|
|
console.warn("Known error for parse date in DateSelect: ", error)
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (formState.isSubmitting) return
|
|
|
|
if (!(day && month && year) && dateValue) {
|
|
setValue(DateName.day, Number(dateValue.day))
|
|
setValue(DateName.month, Number(dateValue.month))
|
|
setValue(DateName.year, Number(dateValue.year))
|
|
}
|
|
}, [setValue, formState.isSubmitting, dateValue, day, month, year])
|
|
|
|
return (
|
|
<DatePicker
|
|
aria-label={intl.formatMessage({ id: "Select date of birth" })}
|
|
isRequired={!!registerOptions.required}
|
|
isInvalid={!formState.isValid}
|
|
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} ${fieldState.invalid ? styles.invalid : ""}`}
|
|
>
|
|
<Select
|
|
aria-label={dayLabel}
|
|
items={days}
|
|
label={dayLabel}
|
|
name={DateName.day}
|
|
onSelect={(key: Key) =>
|
|
setValue(DateName.day, Number(key))
|
|
}
|
|
required
|
|
tabIndex={3}
|
|
value={segment.isPlaceholder ? undefined : segment.value}
|
|
/>
|
|
</div>
|
|
)
|
|
case "month":
|
|
return (
|
|
<div
|
|
className={`${styles.month} ${fieldState.invalid ? styles.invalid : ""}`}
|
|
>
|
|
<Select
|
|
aria-label={monthLabel}
|
|
items={months}
|
|
label={monthLabel}
|
|
name={DateName.month}
|
|
onSelect={(key: Key) =>
|
|
setValue(DateName.month, Number(key))
|
|
}
|
|
required
|
|
tabIndex={2}
|
|
value={segment.isPlaceholder ? undefined : segment.value}
|
|
/>
|
|
</div>
|
|
)
|
|
case "year":
|
|
return (
|
|
<div
|
|
className={`${styles.year} ${fieldState.invalid ? styles.invalid : ""}`}
|
|
>
|
|
<Select
|
|
aria-label={yearLabel}
|
|
items={years}
|
|
label={yearLabel}
|
|
name={DateName.year}
|
|
onSelect={(key: Key) =>
|
|
setValue(DateName.year, Number(key))
|
|
}
|
|
required
|
|
tabIndex={1}
|
|
value={segment.isPlaceholder ? undefined : segment.value}
|
|
/>
|
|
</div>
|
|
)
|
|
default:
|
|
/** DateInput forces return of ReactElement */
|
|
return <></>
|
|
}
|
|
}}
|
|
</DateInput>
|
|
</Group>
|
|
<ErrorMessage errors={formState.errors} name={field.name} />
|
|
</DatePicker>
|
|
)
|
|
}
|
|
|
|
function getDaysInMonth(year: number | null, month: number | null): number {
|
|
if (month === null) {
|
|
return 31
|
|
}
|
|
|
|
// If month is February and no year selected, return minimum.
|
|
if (month === 1 && !year) {
|
|
return 28
|
|
}
|
|
|
|
const yearToUse = year ?? new Date().getFullYear()
|
|
return dt(`${yearToUse}-${month + 1}-01`).daysInMonth()
|
|
}
|