utils.ts
| 1 | import Toastify from "toastify-js"; |
| 2 | import { FileDisplay, type PlaylistItem } from "./types"; |
| 3 | |
| 4 | export function sleep(ms: number) { |
| 5 | return new Promise((resolve) => setTimeout(resolve, ms)); |
| 6 | } |
| 7 | |
| 8 | //join string and dedup slashes and make sure it doesn't start or end with a slash |
| 9 | export function joinPath(...paths: string[]): string { |
| 10 | return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, ""); |
| 11 | } |
| 12 | |
| 13 | //dirname("a/b/c") = "a/b", dirname("a") = "" |
| 14 | export function dirname(path: string): string { |
| 15 | return path.split("/").slice(0, -1).join("/"); |
| 16 | } |
| 17 | |
| 18 | export function basename(path: string): string { |
| 19 | return path.split("/").toReversed()[0]; |
| 20 | } |
| 21 | |
| 22 | //yields each ancestor directory, immediate parent first: parentPaths("a/b/c") yields "a/b", "a" |
| 23 | export function* parentPaths(path: string): Generator<string> { |
| 24 | let current = path; |
| 25 | while (true) { |
| 26 | const lastSlash = current.lastIndexOf("/"); |
| 27 | if (lastSlash === -1) return; |
| 28 | current = current.substring(0, lastSlash); |
| 29 | yield current; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | //directories sort before files, names compare naturally ("track 2" before "track 10") |
| 34 | export function compareDirFirst(aName: string, aIsDir: boolean, bName: string, bIsDir: boolean): number { |
| 35 | if (aIsDir !== bIsDir) return aIsDir ? -1 : 1; |
| 36 | return aName.localeCompare(bName, undefined, { numeric: true }); |
| 37 | } |
| 38 | |
| 39 | export function formatTime(seconds: number): string { |
| 40 | const mins = Math.floor(seconds / 60); |
| 41 | const secs = Math.floor(seconds % 60); |
| 42 | return `${mins}:${secs < 10 ? "0" : ""}${secs}`; |
| 43 | } |
| 44 | |
| 45 | export const LocalStorageValues = { |
| 46 | options: "Options", |
| 47 | volume: "Volume", |
| 48 | playlist: "Playlist", |
| 49 | shuffle: "Shuffle", |
| 50 | repeat: "Repeat", |
| 51 | offline: "Offline", |
| 52 | path: "Path", |
| 53 | fileBrowserButtons: "FileBrowserButtons", |
| 54 | playlistButtons: "PlaylistButtons", |
| 55 | playerControls: "PlayerControls", |
| 56 | }; |
| 57 | |
| 58 | export function generateUUID() { |
| 59 | return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { |
| 60 | const r = (Math.random() * 16) | 0; |
| 61 | const v = c === "x" ? r : (r & 0x3) | 0x8; |
| 62 | return v.toString(16); |
| 63 | }); |
| 64 | } |
| 65 | |
| 66 | function stringErr(e: unknown) { |
| 67 | return e && typeof e === "object" && "message" in e ? e.message : e; |
| 68 | } |
| 69 | |
| 70 | export function toast(text: string, type: "progress" | "info" | "error" | "success", e?: unknown) { |
| 71 | if (e) { |
| 72 | console.error(e); |
| 73 | } |
| 74 | const thisToast = Toastify({ |
| 75 | text: e ? `${text}:\n${stringErr(e)}` : text, |
| 76 | duration: type === "progress" ? -1 : 2000, |
| 77 | close: true, |
| 78 | style: { |
| 79 | "border-radius": "0", |
| 80 | display: "flex", |
| 81 | "align-items": "center", |
| 82 | background: |
| 83 | type === "success" |
| 84 | ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))" |
| 85 | : type === "error" |
| 86 | ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))" |
| 87 | : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))", |
| 88 | }, |
| 89 | }); |
| 90 | thisToast.showToast(); |
| 91 | return thisToast; |
| 92 | } |
| 93 | |
| 94 | export function remoteLog(e: unknown) { |
| 95 | //absolute path and a catch, so the error logger can't itself throw an unhandled rejection while offline |
| 96 | fetch("/remote-log", { body: JSON.stringify(e?.toString()), method: "POST", credentials: "same-origin" }).catch( |
| 97 | () => {}, |
| 98 | ); |
| 99 | } |
| 100 | |
| 101 | //debounce so a burst of failing requests (e.g. many covers loading at once) shows a single notification |
| 102 | let lastUnauthorized = 0; |
| 103 | |
| 104 | //registered by the app root so a 401 anywhere can update the logged-in state |
| 105 | let onUnauthorized: (() => void) | undefined; |
| 106 | export function setUnauthorizedHandler(handler: () => void) { |
| 107 | onUnauthorized = handler; |
| 108 | } |
| 109 | |
| 110 | export function handleUnauthorized(response?: Response | { status?: number } | void): boolean { |
| 111 | if (response?.status !== 401) return false; |
| 112 | //not debounced: keeps the logged-in state correct even while the toast is throttled |
| 113 | onUnauthorized?.(); |
| 114 | const now = Date.now(); |
| 115 | if (now - lastUnauthorized > 3000) { |
| 116 | lastUnauthorized = now; |
| 117 | toast("Unauthorized, please sign in", "error"); |
| 118 | } |
| 119 | return true; |
| 120 | } |
| 121 | |
| 122 | //registered by the app root so a listing the user may not see resets navigation to the top level |
| 123 | let onForbiddenPath: (() => void) | undefined; |
| 124 | export function setForbiddenPathHandler(handler: () => void) { |
| 125 | onForbiddenPath = handler; |
| 126 | } |
| 127 | |
| 128 | export function handleForbiddenPath(response?: Response | { status?: number } | void): boolean { |
| 129 | if (response?.status !== 403) return false; |
| 130 | onForbiddenPath?.(); |
| 131 | toast("That folder is not available to you, returning to the top level", "error"); |
| 132 | return true; |
| 133 | } |
| 134 | |
| 135 | export function formatBytes(bytes: number): string { |
| 136 | if (bytes === 0) return "Queued..."; |
| 137 | |
| 138 | const k = 1024; |
| 139 | const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; |
| 140 | const i = Math.floor(Math.log(bytes) / Math.log(k)); |
| 141 | const value = bytes / k ** i; |
| 142 | |
| 143 | return `${value.toFixed(2)} ${sizes[i]}`; |
| 144 | } |
| 145 | |
| 146 | export function unproxy<T>(value: T): T { |
| 147 | return JSON.parse(JSON.stringify(value)); |
| 148 | } |
| 149 | |
| 150 | function getItemName(item: Pick<PlaylistItem, "path">): string; |
| 151 | function getItemName(item: Pick<PlaylistItem, "path"> | null): string | undefined; |
| 152 | function getItemName(item: Pick<PlaylistItem, "path"> | null) { |
| 153 | if (!item) return undefined; |
| 154 | return basename(item.path); |
| 155 | } |
| 156 | |
| 157 | export function formatFilename(file: Omit<PlaylistItem, "id">, format: FileDisplay): string { |
| 158 | switch (format) { |
| 159 | case FileDisplay.FILENAME: |
| 160 | return getItemName(file); |
| 161 | case FileDisplay.TITLE: |
| 162 | return file.metadata.title || getItemName(file); |
| 163 | case FileDisplay.TRACKNO_TITLE: { |
| 164 | if (!file.metadata.title) return getItemName(file); |
| 165 | const prefix = file.metadata.trackNumber ? `${file.metadata.trackNumber}. ` : ""; |
| 166 | return `${prefix}${file.metadata.title}`; |
| 167 | } |
| 168 | } |
| 169 | throw new Error(`unhandled: ${format}`); |
| 170 | } |
| 171 |