-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathformatters.ts
More file actions
247 lines (206 loc) · 7.21 KB
/
formatters.ts
File metadata and controls
247 lines (206 loc) · 7.21 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import cronstrue from 'cronstrue';
import Admin from '@clients/common/flyteidl/admin';
import Protobuf from '@clients/common/flyteidl/protobuf';
import moment from 'moment-timezone';
import { unknownValueString, zeroSecondsString } from '@clients/common/constants';
import { timezone } from './timezone';
import { durationToMilliseconds, isValidDate } from './utils';
const defaultUTCFormat = 'l LTS';
/** Formats a date into a standard string with a moment-style "from now" hint
* ex. 12/21/2017 8:19:36 PM (18 days ago)
*/
export function dateWithFromNow(input: Date) {
if (!isValidDate(input)) {
return unknownValueString;
}
const date = moment.utc(input);
return `${date.format(defaultUTCFormat)} UTC (${date.fromNow()})`;
}
/** Formats a date into a moment-style "from now" value */
export function dateFromNow(input: Date) {
if (!isValidDate(input)) {
return unknownValueString;
}
const date = moment(input);
return `${date.fromNow()}`;
}
/** Formats a date into a standard format used throughout the UI
* ex 12/21/2017 8:19:36 PM
*/
export function formatDate(input: Date, formatString?: string) {
return isValidDate(input)
? moment(input).format(formatString || defaultUTCFormat)
: unknownValueString;
}
/** Formats a date into a standard UTC format used throughout the UI
* ex 12/21/2017 8:19:36 PM UTC
*/
export function formatDateUTC(input: Date, formatString?: string) {
return isValidDate(input)
? `${moment.utc(input).format(formatString || defaultUTCFormat)} UTC`
: unknownValueString;
}
/**
* Gets human-readable date relative to "now"
*/
export function formateDateRelative(input: Date, threshold = 24 * 60 * 60 * 1000) {
if (!isValidDate(input)) {
return unknownValueString;
}
const diff = moment.utc().diff(moment.utc(input));
if (diff <= threshold) {
return moment.utc(input).fromNow();
}
return formatDate(input, 'YYYY-MM-DD HH:MM A');
}
/** Formats a date into a standard local format used throughout the UI
* ex 12/21/2017 8:19:36 PM PDT
*/
export function formatDateLocalTimezone(input: Date) {
return isValidDate(input) ? moment(input).tz(timezone).format('l LTS z') : unknownValueString;
}
/** Outputs a value in milliseconds in (H M S) format (ex. 2h 3m 30s) */
export function millisecondsToHMS(valueMS: number): string {
if (valueMS < 0) {
return unknownValueString;
}
if (valueMS === 0) {
return zeroSecondsString;
}
if (valueMS < 1000) {
return `${valueMS}ms`;
}
const duration = moment.duration(valueMS);
const parts: string[] = [];
// Using asHours() because if it's greater than 24, we'll just show the total
if (duration.asHours() >= 1) {
parts.push(`${Math.floor(duration.asHours())}h`);
}
if (duration.minutes() >= 1) {
parts.push(`${duration.minutes()}m`);
}
if (duration.seconds() >= 1) {
// there may be a bug in Momemt.js that shows float number of seconds, so rounding it down to make sure it will be int
parts.push(`${Math.floor(duration.seconds())}s`);
}
return parts.length ? parts.join(' ') : unknownValueString;
}
/** Outputs a value in moment.Duration in (Y M D H M S) format (ex. 1y 1M 1d 2h 3m 30s) */
export function durationToYMWDHMS(duration: moment.Duration): string {
if (duration.asSeconds() === 0) {
return '';
}
const parts: string[] = [];
if (duration.years() !== 0) {
parts.push(`${Math.abs(duration.years())}y`);
}
if (duration.months() !== 0) {
parts.push(`${Math.abs(duration.months())}M`);
}
// ISO-8601 does not permit mixing between the PnYnMnD and PnW formats.
// Any week-based input is multiplied by 7 and treated as a number of days.
// However moment can parse the mixture resulting both a number of weeks and a number of days.
// For example both P8D and P1W1D result duration.weeks() == 1 and duration.days() == 8.
// Here we skip showing weeks and only take the total number of days.
if (duration.days() !== 0) {
parts.push(`${Math.abs(duration.days())}d`);
}
if (duration.hours() !== 0) {
parts.push(`${Math.abs(duration.hours())}h`);
}
if (duration.minutes() !== 0) {
parts.push(`${Math.abs(duration.minutes())}m`);
}
if (duration.seconds() !== 0) {
parts.push(`${Math.abs(duration.seconds())}s`);
}
const now = moment();
const sign = now.clone().add(duration).isBefore(now) ? '-' : '+';
return `(${sign}) ${parts.join(' ')}`;
}
/** Converts a protobuf Duration value to (H M S) format (ex. 2h 3m 30s) */
export function protobufDurationToHMS(duration: Protobuf.IDuration) {
return millisecondsToHMS(durationToMilliseconds(duration));
}
/** Calculates the difference between two Dates and outputs it in (H M S) format (ex. 2h 3m 30s)
*/
export function dateDiffString(fromDate: Date, toDate: Date) {
if (!isValidDate(fromDate) || !isValidDate(toDate)) {
return unknownValueString;
}
return millisecondsToHMS(moment(toDate).diff(fromDate));
}
const fixedRateUnitStrings = {
[Admin.FixedRateUnit.DAY]: 'days',
[Admin.FixedRateUnit.HOUR]: 'hours',
[Admin.FixedRateUnit.MINUTE]: 'minutes',
};
/** Converts a IFixedRate value into a human-readable string ('Every x minutes/hours/days') */
export function fixedRateToString({ value, unit }: Admin.IFixedRate): string {
if (unit == null || !(unit in Admin.FixedRateUnit) || !value) {
return '';
}
return `Every ${value} ${fixedRateUnitStrings[unit]}`;
}
const hourlyAliases = ['@hourly', 'hourly', 'hours'];
const dailyAliases = ['@daily', 'daily', 'days'];
const weeklyAliases = ['@weekly', 'weekly', 'weeks'];
const monthlyAliases = ['@monthly', 'monthly', 'months'];
const yearlyAliases = ['@yearly', 'yearly', 'years', '@annually', 'annually'];
export function getScheduleFrequencyStringFromAlias(schedule: string) {
if (hourlyAliases.includes(schedule)) {
return 'Every hour';
}
if (dailyAliases.includes(schedule)) {
return 'Every day';
}
if (weeklyAliases.includes(schedule)) {
return 'Every week';
}
if (monthlyAliases.includes(schedule)) {
return 'Every month';
}
if (yearlyAliases.includes(schedule)) {
return 'Every year';
}
return '';
}
export function getScheduleFrequencyString(schedule?: Admin.ISchedule) {
if (schedule == null) {
return '';
}
if (schedule.rate) {
return fixedRateToString(schedule.rate);
}
if (schedule.cronSchedule?.schedule) {
return (
getScheduleFrequencyStringFromAlias(schedule.cronSchedule.schedule) ||
cronstrue.toString(schedule.cronSchedule.schedule)
);
}
return '';
}
export function getScheduleOffsetString(schedule?: Admin.ISchedule) {
if (schedule == null) {
return '';
}
if (schedule.cronSchedule && schedule.cronSchedule.offset) {
return durationToYMWDHMS(moment.duration(schedule.cronSchedule.offset));
}
return '';
}
/** Ensures that a given string has a protocol prefix. If not, will add https:// to the beginning */
export function ensureUrlWithProtocol(url: string): string {
if (url.indexOf('http') !== 0) {
return `https://${url}`;
}
return url;
}
/** Formats a number into a string with leading zeros to ensure a consistent
* width.
* Example: 1 will be '01'
* 10 will be '10'
*/
export function leftPaddedNumber(value: number, length: number): string {
return value.toString().padStart(length, '0');
}