UNPKG

@navinc/base-react-components

Version:
48 lines 2.59 kB
import { useRef, useState } from 'react'; import { createProxyWithOverrides, DATE_FORMAT_ISO8601_DATE, formatDate, parseDate } from '@navinc/utils'; const isDateValid = (v) => !isNaN(v.getTime()); const isSameDate = (a, b) => (a === null || a === void 0 ? void 0 : a.getTime()) === (b === null || b === void 0 ? void 0 : b.getTime()); // TODO: Unit tests @Jayce export const useDatePickerInput = (incomingValue, { name, onChange, withYear, withMonth, withDay, } = {}) => { const incomingValueRef = useRef(undefined); const valueRef = useRef(undefined); const internalValueRef = useRef(''); const [_, triggerRender] = useState({}); if (!isSameDate(incomingValue, incomingValueRef.current) && !isSameDate(valueRef.current, incomingValue)) { valueRef.current = incomingValue; internalValueRef.current = incomingValue && isDateValid(incomingValue) ? formatDate(incomingValue, DATE_FORMAT_ISO8601_DATE) : ''; } incomingValueRef.current = incomingValue; const [yearValue = withYear === false ? '1' : '', monthValue = withMonth === false ? '01' : '', dayValue = withDay === false ? '01' : '',] = internalValueRef.current.split('-'); const triggerChange = (updatedInternalValue, e) => { const updatedEvent = e; internalValueRef.current = updatedInternalValue; const dateValue = parseDate(internalValueRef.current); const propagatedValue = isDateValid(dateValue) ? dateValue : undefined; valueRef.current = propagatedValue; updatedEvent.target = createProxyWithOverrides(updatedEvent.target, Object.assign(Object.assign({}, (name ? { name } : {})), { value: propagatedValue })); triggerRender({}); // to update the input value onChange === null || onChange === void 0 ? void 0 : onChange(updatedEvent); }; const yearProps = { value: yearValue, onChange: (e) => { triggerChange(`${e.target.value}-${monthValue}-${dayValue}`, e); }, }; const monthProps = { value: monthValue, onChange: (e) => { triggerChange(`${yearValue}-${e.target.value}-${dayValue}`, e); }, }; const dayProps = { value: dayValue, onChange: (e) => { triggerChange(`${yearValue}-${monthValue}-${e.target.value}`, e); }, }; return Object.assign(Object.assign(Object.assign({}, (withYear !== false ? { yearProps } : {})), (withMonth !== false ? { monthProps } : {})), (withDay !== false ? { dayProps } : {})); }; //# sourceMappingURL=use-date-picker-input.js.map