UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

80 lines (79 loc) 2.29 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useInputDates; exports.pad = pad; var _dateFns = require("date-fns"); var _react = require("react"); function useInputDates({ startDate, endDate }) { const [previousDates, setPreviousDates] = (0, _react.useState)({ startDate, endDate }); const [inputDates, setInputDates] = (0, _react.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 = (0, _react.useCallback)(dates => { setInputDates(current => ({ ...current, ...dates })); }, []); return { inputDates, updateInputDates }; } const inputDateFormatter = { day: date => pad((0, _dateFns.format)(date, 'dd'), 2), month: date => pad((0, _dateFns.format)(date, 'MM'), 2), year: date => (0, _dateFns.format)(date, 'yyyy') }; function formatInputDate(type, date) { return (0, _dateFns.isValid)(date) ? inputDateFormatter[type](date) : null; } function getInputDates(type, date) { if ((0, _dateFns.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 {}; } function pad(date, size) { const dateWithPadding = '000000000' + date; return dateWithPadding.substring(dateWithPadding.length - size); } //# sourceMappingURL=useInputDates.js.map