-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.ts
More file actions
86 lines (78 loc) · 2.46 KB
/
util.ts
File metadata and controls
86 lines (78 loc) · 2.46 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
import { FileI } from "./file";
/**
* convert the size of a file into a human-readable form
* @param size the size of a file in bytes
* @param decimals how many decimals should be displayed
* @returns the file size in bytes, kilobytes etc.
*/
export function convertFileSize(size: number, decimals = 1): string {
if (size === 0) return "";
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(size) / Math.log(k));
return `${parseFloat((size / Math.pow(k, i)).toFixed(dm))}${sizes[i]}`;
}
/**
* normalises the files from the backend for correct usage
* @param files the files that should be converted
* @returns a normalised file array
*/
export function convertFiles(files: FileI[]): FileI[] {
return files
.map((f) => ({
...f,
created: f.created ? new Date(f.created) : undefined,
modified: f.modified ? new Date(f.modified) : undefined,
}))
.sort((a, b) => {
if (a.type === b.type) {
return a.name.localeCompare(b.name);
}
if (a.type === "FOLDER") {
return -1;
}
return 1;
});
}
/**
* find the nearest parent of an element with the classname
* @param className the classname to search for
* @param el the element from which to search from
* @returns the nearest parent with the supplied classname, or undefiend if not found
*/
export function findElInTree(
className: string,
el?: HTMLElement | null
): HTMLElement | undefined {
if (!el || el === document.documentElement) {
return undefined;
}
if (el.classList.contains(className)) {
return el;
}
return findElInTree(className, el.parentElement);
}
/**
* normalises an URL for later API usage
* @param url the url to be normalised
* @param endingSlash if the URL should have an ending slash
* @param leadingSlash if the URL should have a leading slash
* @returns the normalised URL
*/
export function normalizeURL(url: string, endingSlash = true, leadingSlash = false): string {
url = url.trim();
if (url === "/") {
if (!leadingSlash && !endingSlash) return "";
}
if (!endingSlash && url.endsWith("/")) url = url.substring(0, url.length - 1);
if (endingSlash && !url.endsWith("/")) url = url + "/";
if (leadingSlash && !url.startsWith("/")) url = "/" + url;
if (!leadingSlash && url.startsWith("/")) url = url.substring(1);
return url;
}
export function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => resolve(), ms);
});
}