utils.ts
⎇
Raw
1import Toastify from "toastify-js";
2
3export function sleep(ms: number) {
4 return new Promise((resolve) => setTimeout(resolve, ms));
5}
6
7//join string and dedup slashes and make sure it doesn't start with a slash
8export function joinPath(...paths: string[]): string {
9 return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "");
10}
11
12export function formatTime(seconds: number): string {
13 const mins = Math.floor(seconds / 60);
14 const secs = Math.floor(seconds % 60);
15 return `${mins}:${secs < 10 ? "0" : ""}${secs}`;
16}
17
18export const LocalStorageValues = {
19 options: "Options",
20 volume: "Volume",
21 playlist: "Playlist",
22 shuffle: "Shuffle",
23 repeat: "Repeat",
24 offline: "Offline",
25 path: "Path",
26};
27
28export function generateUUID() {
29 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
30 const r = (Math.random() * 16) | 0;
31 const v = c === "x" ? r : (r & 0x3) | 0x8;
32 return v.toString(16);
33 });
34}
35
36function stringErr(e: unknown) {
37 return e && typeof e === "object" && "message" in e ? e.message : e;
38}
39
40export function toast(text: string, type: "info" | "error" | "sucess", e?: unknown) {
41 if (e) console.error(e);
42 Toastify({
43 text: e ? `${text}:\n${stringErr(e)}` : text,
44 duration: 20000,
45 close: true,
46 style: {
47 display: "flex",
48 "align-items": "center",
49 background:
50 type === "sucess"
51 ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))"
52 : type === "error"
53 ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))"
54 : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))",
55 },
56 }).showToast();
57}
58
59export function toastError() {}
60
61export function formatBytes(bytes: number): string {
62 if (bytes === 0) return "0 Bytes";
63
64 const k = 1024;
65 const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
66 const i = Math.floor(Math.log(bytes) / Math.log(k));
67 const value = bytes / k ** i;
68
69 return `${Number.parseFloat(value.toFixed(2))} ${sizes[i]}`;
70}
71