Debian Codegraph @

node/@patternfly/react-core/src/components/Timestamp/Timestamp.tsx

raw
1 import { useEffect, useState } from 'react';
2 import styles from '@patternfly/react-styles/css/components/Timestamp/timestamp';
3 import { css } from '@patternfly/react-styles';
4 import { Tooltip } from '../Tooltip';
5 import { isValidDate } from '../../helpers/datetimeUtils';
6
7 export enum TimestampFormat {
8 full = 'full',
9 long = 'long',
10 medium = 'medium',
11 short = 'short'
12 }
13
14 export enum TimestampTooltipVariant {
15 default = 'default',
16 custom = 'custom'
17 }
18
19 export interface TimestampTooltip {
20 /** The variant of the tooltip. The "default" variant displays the date passed into
21 * the timestamp's date prop as a UTC string.
22 */
23 variant: 'default' | 'custom';
24 /** Content displayed in the tooltip when using the "custom" variant. */
25 content?: React.ReactNode;
26 /** Additional props passed to the tooltip. */
27 tooltipProps?: any;
28 /** A custom suffix to apply to a "default" variant tooltip. */
29 suffix?: string;
30 }
31
32 export interface TimestampProps extends React.HTMLProps<HTMLSpanElement> {
33 /** Displays custom content inside the timestamp, such as a relative time. This prop will
34 * override the default content that is displayed. Custom content will not be affected by
35 * any props that format or add to displayed content.
36 */
37 children?: React.ReactNode;
38 /** Class to add to the outer span. */
39 className?: string;
40 /** Applies custom formatting to the displayed date and/or time. Passing this prop in will
41 * override the dateFormat and timeFormat props.
42 */
43 customFormat?: { [key: string]: string };
44 /** Determines the default content that is displayed inside the timestamp and the value of
45 * the inner time element's datetime attribute. */
46 date?: Date;
47 /** Determines the format of the displayed date in the timestamp and UTC tooltip. Examples:
48 * "Full" => Tuesday, August 9, 2022;
49 * "Long" => August 9, 2022;
50 * "Medium" => Aug 9, 2022;
51 * "Short" => 8/9/22
52 */
53 dateFormat?: 'full' | 'long' | 'medium' | 'short';
54 /** Applies a custom suffix to the displayed content, usually after the time, such as a
55 * custom time zone.
56 */
57 displaySuffix?: string;
58 /** Flag for displaying the time in a 12 hour format. If this prop is not passed in,
59 * the hour format will be based on the locale prop's value.
60 */
61 is12Hour?: boolean;
62 /** Determines which locale to use in the displayed content. Defaults to the current locale
63 * when this prop is not passed in. For more information about locale's:
64 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation
65 */
66 locale?: string;
67 /** Flag indicating whether the default content should be displayed as a UTC string
68 * instead of a local string.
69 */
70 shouldDisplayUTC?: boolean;
71 /** Determines the format of the displayed time in the timestamp and UTC tooltip. Examples:
72 * "Full" => 11:25:00 AM Eastern Daylight Time
73 * "Long" => 11:25:00 AM EDT
74 * "Medium" => 11:25:00 AM
75 * "Short" => 11:25 AM
76 */
77 timeFormat?: 'full' | 'long' | 'medium' | 'short';
78 /** Adds a tooltip to the timestamp. */
79 tooltip?: TimestampTooltip;
80 }
81
82 export const Timestamp: React.FunctionComponent<TimestampProps> = ({
83 children,
84 className,
85 customFormat,
86 date: dateProp,
87 dateFormat,
88 displaySuffix = '',
89 is12Hour,
90 locale,
91 shouldDisplayUTC,
92 timeFormat,
93 tooltip,
94 ...props
95 }: TimestampProps) => {
96 const [date, setDate] = useState(() => {
97 const initDate = new Date(dateProp);
98 if (isValidDate(initDate)) {
99 return initDate;
100 }
101
102 return new Date();
103 });
104
105 useEffect(() => {
106 const dateFromProp = new Date(dateProp);
107 if (isValidDate(dateFromProp) && dateFromProp.toString() !== new Date(date).toString()) {
108 setDate(dateFromProp);
109 } else if (!dateProp) {
110 setDate(new Date());
111 }
112 }, [dateProp]);
113
114 const hasTimeFormat = timeFormat && !customFormat;
115 const formatOptions = {
116 ...(dateFormat && !customFormat && { dateStyle: dateFormat }),
117 ...(customFormat && { ...customFormat }),
118 ...(is12Hour !== undefined && { hour12: is12Hour })
119 };
120
121 const dateAsLocaleString = new Date(date).toLocaleString(locale, {
122 ...formatOptions,
123 ...(hasTimeFormat && { timeStyle: timeFormat })
124 });
125
126 const utcTimeFormat = timeFormat !== 'short' ? 'medium' : 'short';
127 const convertToUTCString = (date: Date) => new Date(date).toUTCString().slice(0, -3);
128 const utcDateString = new Date(convertToUTCString(date)).toLocaleString(locale, {
129 ...formatOptions,
130 ...(hasTimeFormat && { timeStyle: utcTimeFormat })
131 });
132 const defaultUTCSuffix = timeFormat === 'full' ? 'Coordinated Universal Time' : 'UTC';
133 const createUTCContent = (customSuffix: string) =>
134 `${utcDateString} ${customSuffix ? customSuffix : defaultUTCSuffix}`;
135
136 const defaultDisplay = shouldDisplayUTC
137 ? createUTCContent(displaySuffix)
138 : `${dateAsLocaleString}${displaySuffix ? ' ' + displaySuffix : ''}`;
139 const { dateTime, ...propsWithoutDateTime } = props;
140
141 const timestamp = (
142 <span
143 className={css(styles.timestamp, tooltip && styles.modifiers.helpText, className)}
144 {...(tooltip && { tabIndex: 0 })}
145 {...propsWithoutDateTime}
146 >
147 <time className={`${styles.timestamp}__text`} dateTime={dateTime || new Date(date).toISOString()}>
148 {!children ? defaultDisplay : children}
149 </time>
150 </span>
151 );
152
153 return tooltip ? (
154 <Tooltip
155 content={tooltip.variant === TimestampTooltipVariant.default ? createUTCContent(tooltip.suffix) : tooltip.content}
156 {...tooltip.tooltipProps}
157 >
158 {timestamp}
159 </Tooltip>
160 ) : (
161 timestamp
162 );
163 };
164 Timestamp.displayName = 'Timestamp';