@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
95 lines (94 loc) • 3.02 kB
JavaScript
"use strict";
"use client";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = require("react");
var _index = _interopRequireDefault(require("../String/index.js"));
var _useTranslation = _interopRequireDefault(require("../../hooks/useTranslation.js"));
var _Context = _interopRequireDefault(require("../../../../shared/Context.js"));
var _index2 = require("../../Field/Date/index.js");
var _DateFormatUtils = require("../../../../components/date-format/DateFormatUtils.js");
var _DateOfBirth = require("../../Field/DateOfBirth/DateOfBirth.js");
var _withComponentMarkers = _interopRequireDefault(require("../../../../shared/helpers/withComponentMarkers.js"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function DateComponent(props) {
var _props$locale, _props$label;
const translations = (0, _useTranslation.default)().Date;
const {
locale: contextLocale
} = (0, _react.useContext)(_Context.default);
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 = (0, _react.useCallback)(value => {
if (!value) {
return undefined;
}
const isRange = /\|/.test(value);
if (isRange) {
const [startDate, endDate] = (0, _index2.parseRangeValue)(value);
return (0, _DateFormatUtils.formatDateRange)({
startDate,
endDate
}, {
locale,
options
});
}
if (dateFormat && dateFormat !== _DateOfBirth.DEFAULT_DATE_FORMAT) {
return formatCustomDate(value, dateFormat);
}
return (0, _DateFormatUtils.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 (0, _jsxRuntime.jsx)(_index.default, {
...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;
}
}
(0, _withComponentMarkers.default)(DateComponent, {
_supportsSpacingProps: true
});
var _default = exports.default = DateComponent;
//# sourceMappingURL=Date.js.map