CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/components/misc/timestamp.tsx
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { Tooltip } from "antd";
7
import { CSSProperties } from "react";
8
import TimeAgo from "timeago-react";
9
10
interface Props {
11
epoch?: number; // ms since epoch
12
datetime?: Date | string;
13
style?: CSSProperties;
14
dateOnly?: boolean;
15
absolute?: boolean;
16
}
17
18
export function processTimestamp(props: Props) {
19
const { epoch, dateOnly } = props;
20
let datetime = props.datetime;
21
22
if (epoch && datetime == null) {
23
datetime = new Date(epoch);
24
}
25
26
if (!datetime) {
27
return "-";
28
}
29
30
if (typeof datetime == "string") {
31
datetime = new Date(datetime);
32
if (typeof datetime == "string") throw Error("bug");
33
}
34
35
const absoluteTimeDateOnly = datetime.toLocaleDateString(undefined, {
36
year: "numeric",
37
month: "short",
38
day: "numeric",
39
});
40
41
const absoluteTimeFull = datetime.toLocaleString(undefined, {
42
year: "numeric",
43
month: "short",
44
day: "numeric",
45
hour: "numeric",
46
minute: "numeric",
47
});
48
49
const timeShown = dateOnly ? absoluteTimeDateOnly : absoluteTimeFull;
50
51
return { datetime, timeShown, absoluteTimeDateOnly, absoluteTimeFull };
52
}
53
54
export default function Timestamp(props: Props) {
55
const { style, absolute } = props;
56
const data = processTimestamp(props);
57
if (data === "-") {
58
return <span style={style}>-</span>;
59
}
60
const { datetime, timeShown, absoluteTimeFull } = data;
61
62
if (absolute) {
63
return (
64
<Tooltip trigger={["hover", "click"]} title={absoluteTimeFull}>
65
<span style={style}>{timeShown}</span>
66
</Tooltip>
67
);
68
}
69
70
return (
71
<Tooltip trigger={["hover", "click"]} title={timeShown}>
72
<TimeAgo style={style} datetime={datetime} />
73
</Tooltip>
74
);
75
}
76
77