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" | "success", e?: unknown) {
41 if (e) console.error(e);
42 const thisToast = Toastify({
43 text: e ? `${text}:\n${stringErr(e)}` : text,
44 duration: 20000,
45 close: true,
46 style: {
47 "border-radius": "0",
48 display: "flex",
49 "align-items": "center",
50 background:
51 type === "success"
52 ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))"
53 : type === "error"
54 ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))"
55 : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))",
56 },
57 });
58 thisToast.showToast;
59 return thisToast;
60}
61
62export function toastError() {}
63
64export function formatBytes(bytes: number): string {
65 if (bytes === 0) return "0 Bytes";
66
67 const k = 1024;
68 const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
69 const i = Math.floor(Math.log(bytes) / Math.log(k));
70 const value = bytes / k ** i;
71
72 return `${value.toFixed(2)} ${sizes[i]}`;
73}
74