Merge branch '15256-removing-files-during-upload'
[arvados-workbench2.git] / src / common / formatters.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { PropertyValue } from "~/models/search-bar";
6 import { Vocabulary, getTagKeyLabel, getTagValueLabel } from "~/models/vocabulary";
7
8 export const formatDate = (isoDate?: string | null, utc: boolean = false) => {
9     if (isoDate) {
10         const date = new Date(isoDate);
11         let text: string;
12         if (utc) {
13             text = date.toUTCString();
14         }
15         else {
16             text = date.toLocaleString();
17         }
18         return text === 'Invalid Date' ? "(none)" : text;
19     }
20     return "(none)";
21 };
22
23 export const formatFileSize = (size?: number) => {
24     if (typeof size === "number") {
25         for (const { base, unit } of FILE_SIZES) {
26             if (size >= base) {
27                 return `${(size / base).toFixed()} ${unit}`;
28             }
29         }
30     }
31     return "";
32 };
33
34 export const formatTime = (time: number) => {
35     const minutes = Math.floor(time / (1000 * 60) % 60).toFixed(0);
36     const hours = Math.floor(time / (1000 * 60 * 60)).toFixed(0);
37
38     return hours + "h " + minutes + "m";
39 };
40
41 export const getTimeDiff = (endTime: string, startTime: string) => {
42     return new Date(endTime).getTime() - new Date(startTime).getTime();
43 };
44
45 export const formatProgress = (loaded: number, total: number) => {
46     const progress = loaded >= 0 && total > 0 ? loaded * 100 / total : 0;
47     return `${progress.toFixed(2)}%`;
48 };
49
50 export function formatUploadSpeed(prevLoaded: number, loaded: number, prevTime: number, currentTime: number) {
51     const speed = loaded > prevLoaded && currentTime > prevTime
52         ? (loaded - prevLoaded) / (currentTime - prevTime)
53         : 0;
54     return `${(speed / 1000).toFixed(2)} KB/s`;
55 }
56
57 const FILE_SIZES = [
58     {
59         base: 1000000000000,
60         unit: "TB"
61     },
62     {
63         base: 1000000000,
64         unit: "GB"
65     },
66     {
67         base: 1000000,
68         unit: "MB"
69     },
70     {
71         base: 1000,
72         unit: "KB"
73     },
74     {
75         base: 1,
76         unit: "B"
77     }
78 ];
79
80 export const formatPropertyValue = (pv: PropertyValue, vocabulary?: Vocabulary) => {
81     if (vocabulary && pv.keyID && pv.valueID) {
82         return `${getTagKeyLabel(pv.keyID, vocabulary)}: ${getTagValueLabel(pv.keyID, pv.valueID!, vocabulary)}`;
83     }
84     if (pv.key) {
85         return pv.value
86             ? `${pv.key}: ${pv.value}`
87             : pv.key;
88     }
89     return "";
90 };