UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

83 lines (82 loc) 2.46 kB
"use client"; import React, { useCallback, useContext } from 'react'; import StringValue from "../String/index.js"; import useTranslation from "../../hooks/useTranslation.js"; import SharedContext from "../../../../shared/Context.js"; import { parseRangeValue } from "../../Field/Date/index.js"; import { formatDate, formatDateRange } from "../../../../components/date-format/DateFormatUtils.js"; import { DEFAULT_DATE_FORMAT } from "../../Field/DateOfBirth/DateOfBirth.js"; function DateComponent(props) { var _props$locale, _props$label; const translations = useTranslation().Date; const { locale: contextLocale } = useContext(SharedContext); const locale = (_props$locale = props.locale) !== null && _props$locale !== void 0 ? _props$locale : contextLocale; const { dateFormat, variant = 'long' } = props; const options = convertVariantToDateStyle(variant); const toInput = useCallback(value => { if (!value) { return undefined; } const isRange = /\|/.test(value); if (isRange) { const [startDate, endDate] = parseRangeValue(value); return formatDateRange({ startDate, endDate }, { locale, options }); } if (dateFormat && dateFormat !== DEFAULT_DATE_FORMAT) { return formatCustomDate(value, dateFormat); } return formatDate(value, { locale, options }); }, [locale, options, dateFormat]); const stringProps = { ...props, label: (_props$label = props.label) !== null && _props$label !== void 0 ? _props$label : translations.label, toInput }; return React.createElement(StringValue, stringProps); } function convertVariantToDateStyle(variant) { if (variant === 'long') { return { dateStyle: 'long' }; } if (variant === 'short') { return { dateStyle: 'medium' }; } return { dateStyle: 'short' }; } function formatCustomDate(value, dateFormat) { try { const date = new Date(value); if (isNaN(date.getTime())) { return value; } const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return dateFormat.replace('yyyy', year.toString()).replace('MM', month).replace('dd', day); } catch (error) { return value; } } DateComponent._supportsSpacingProps = true; export default DateComponent; //# sourceMappingURL=Date.js.map