Files
SCM-Manager/scm-ui/ui-components/src/DateFromNow.tsx

104 lines
2.2 KiB
TypeScript
Raw Normal View History

import React from "react";
import { withTranslation, WithTranslation } from "react-i18next";
import { formatDistance, format, parseISO, Locale } from "date-fns";
import { enUS, de, es } from "date-fns/locale";
import styled from "styled-components";
type LocaleMap = {
2019-10-21 10:57:56 +02:00
[key: string]: Locale;
};
type DateInput = Date | string;
const supportedLocales: LocaleMap = {
2019-10-09 15:51:49 +02:00
enUS,
en: enUS,
2019-10-09 15:51:49 +02:00
de,
es
2019-10-09 15:51:49 +02:00
};
2019-03-12 10:44:58 +01:00
type Props = WithTranslation & {
date?: DateInput;
timeZone?: string;
/**
* baseDate is the date from which the distance is calculated,
* default is the current time (new Date()). This property
* is required to keep snapshots tests green over the time on
* ci server.
*/
baseDate?: DateInput;
};
type Options = {
addSuffix: boolean;
locale: Locale;
timeZone?: string;
};
2019-10-09 15:51:49 +02:00
const DateElement = styled.time`
border-bottom: 1px dotted rgba(219, 219, 219);
cursor: help;
`;
class DateFromNow extends React.Component<Props> {
getLocale = (): Locale => {
2019-10-09 15:51:49 +02:00
const { i18n } = this.props;
for (const lng of i18n.languages || []) {
const locale = supportedLocales[lng];
if (locale) {
return locale;
}
2019-10-09 15:51:49 +02:00
}
const locale = supportedLocales[i18n.language];
if (locale) {
return locale;
}
return enUS;
2019-10-09 15:51:49 +02:00
};
2019-10-09 15:51:49 +02:00
createOptions = () => {
const { timeZone } = this.props;
const options: Options = {
addSuffix: true,
locale: this.getLocale()
2019-10-09 15:51:49 +02:00
};
if (timeZone) {
options.timeZone = timeZone;
}
return options;
};
toDate = (value: DateInput): Date => {
if (value instanceof Date) {
return value;
}
return parseISO(value);
2019-10-21 10:57:56 +02:00
};
getBaseDate = () => {
const { baseDate } = this.props;
if (baseDate) {
return this.toDate(baseDate);
}
return new Date();
2019-10-09 15:51:49 +02:00
};
2019-10-09 15:51:49 +02:00
render() {
const { date } = this.props;
if (date) {
const isoDate = this.toDate(date);
2019-10-09 15:51:49 +02:00
const options = this.createOptions();
const distance = formatDistance(isoDate, this.getBaseDate(), options);
const formatted = format(isoDate, "yyyy-MM-dd HH:mm:ss", options);
2019-10-09 15:51:49 +02:00
return <DateElement title={formatted}>{distance}</DateElement>;
}
return null;
}
}
export default withTranslation()(DateFromNow);