-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Expand file tree
/
Copy pathuseExpirationText.ts
More file actions
55 lines (44 loc) · 1.71 KB
/
Copy pathuseExpirationText.ts
File metadata and controls
55 lines (44 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { useLanguage } from '@rocket.chat/ui-contexts';
import { isSameDay } from 'date-fns';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useFormatDate } from './useFormatDate';
import { useFormatTime } from './useFormatTime';
// Handles Date, ISO string, and EJSON { $date } (from DDP streamer which does raw JSON.parse without EJSON deserialization)
function parseExpiresAt(value?: unknown): Date | undefined {
if (!value) {
return undefined;
}
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? undefined : value;
}
if (typeof value === 'object' && '$date' in (value as Record<string, unknown>)) {
const date = new Date((value as { $date: number }).$date);
return Number.isNaN(date.getTime()) ? undefined : date;
}
if (typeof value === 'string') {
const date = new Date(value);
return Number.isNaN(date.getTime()) ? undefined : date;
}
return undefined;
}
export function useExpirationText(statusExpiresAt?: Date | string) {
const { t } = useTranslation();
const language = useLanguage();
const formatTime = useFormatTime();
const formatDate = useFormatDate();
return useMemo(() => {
const expiresAt = parseExpiresAt(statusExpiresAt);
if (!expiresAt || expiresAt.getTime() <= Date.now()) {
return undefined;
}
const now = new Date();
if (isSameDay(expiresAt, now)) {
return t('Until_time', { time: formatTime(expiresAt) });
}
if (expiresAt.getFullYear() === now.getFullYear()) {
return t('Until_date', { date: new Intl.DateTimeFormat(language, { month: 'long', day: 'numeric' }).format(expiresAt) });
}
return t('Until_date', { date: formatDate(expiresAt) });
}, [statusExpiresAt, t, language, formatTime, formatDate]);
}