UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

74 lines (73 loc) 2.1 kB
"use client"; import { format, isValid } from 'date-fns'; import { useCallback, useState } from 'react'; export default function useInputDates({ startDate, endDate }) { const [previousDates, setPreviousDates] = useState({ startDate, endDate }); const [inputDates, setInputDates] = useState({ startDay: formatInputDate('day', startDate), startMonth: formatInputDate('month', startDate), startYear: formatInputDate('year', startDate), endDay: formatInputDate('day', endDate), endMonth: formatInputDate('month', endDate), endYear: formatInputDate('year', endDate) }); const hasStartDateChange = startDate !== previousDates.startDate; const hasEndDateChange = endDate !== previousDates.endDate; if (hasStartDateChange || hasEndDateChange) { setInputDates(currentInputDates => ({ ...currentInputDates, ...(hasStartDateChange && getInputDates('start', startDate)), ...(hasEndDateChange && getInputDates('end', endDate)) })); setPreviousDates({ startDate, endDate }); } const updateInputDates = useCallback(dates => { setInputDates(current => ({ ...current, ...dates })); }, []); return { inputDates, updateInputDates }; } const inputDateFormatter = { day: date => pad(format(date, 'dd'), 2), month: date => pad(format(date, 'MM'), 2), year: date => format(date, 'yyyy') }; function formatInputDate(type, date) { return isValid(date) ? inputDateFormatter[type](date) : null; } function getInputDates(type, date) { if (isValid(date)) { return { [`${type}Day`]: formatInputDate('day', date), [`${type}Month`]: formatInputDate('month', date), [`${type}Year`]: formatInputDate('year', date) }; } if (date === undefined) { return { [`${type}Day`]: null, [`${type}Month`]: null, [`${type}Year`]: null }; } return {}; } export function pad(date, size) { const dateWithPadding = '000000000' + date; return dateWithPadding.substring(dateWithPadding.length - size); } //# sourceMappingURL=useInputDates.js.map