import Toastify from "toastify-js"; import { FileDisplay, type PlaylistItem } from "./types"; export function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } //join string and dedup slashes and make sure it doesn't start or end with a slash export function joinPath(...paths: string[]): string { return paths.join("/").replace(/\/+/g, "/").replace(/^\//, "").replace(/\/$/, ""); } //dirname("a/b/c") = "a/b", dirname("a") = "" export function dirname(path: string): string { return path.split("/").slice(0, -1).join("/"); } export function basename(path: string): string { return path.split("/").toReversed()[0]; } //yields each ancestor directory, immediate parent first: parentPaths("a/b/c") yields "a/b", "a" export function* parentPaths(path: string): Generator { let current = path; while (true) { const lastSlash = current.lastIndexOf("/"); if (lastSlash === -1) return; current = current.substring(0, lastSlash); yield current; } } //directories sort before files, names compare naturally ("track 2" before "track 10") export function compareDirFirst(aName: string, aIsDir: boolean, bName: string, bIsDir: boolean): number { if (aIsDir !== bIsDir) return aIsDir ? -1 : 1; return aName.localeCompare(bName, undefined, { numeric: true }); } export function formatTime(seconds: number): string { const mins = Math.floor(seconds / 60); const secs = Math.floor(seconds % 60); return `${mins}:${secs < 10 ? "0" : ""}${secs}`; } export const LocalStorageValues = { options: "Options", volume: "Volume", playlist: "Playlist", shuffle: "Shuffle", repeat: "Repeat", offline: "Offline", path: "Path", fileBrowserButtons: "FileBrowserButtons", playlistButtons: "PlaylistButtons", playerControls: "PlayerControls", }; export function generateUUID() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); } function stringErr(e: unknown) { return e && typeof e === "object" && "message" in e ? e.message : e; } export function toast(text: string, type: "progress" | "info" | "error" | "success", e?: unknown) { if (e) { console.error(e); } const thisToast = Toastify({ text: e ? `${text}:\n${stringErr(e)}` : text, duration: type === "progress" ? -1 : 2000, close: true, style: { "border-radius": "0", display: "flex", "align-items": "center", background: type === "success" ? "linear-gradient(135deg,rgb(38, 194, 27),rgb(5, 144, 52))" : type === "error" ? "linear-gradient(135deg,rgb(255, 24, 24),rgb(220, 0, 0))" : "linear-gradient(135deg,rgb(50, 60, 255),rgb(34, 37, 209))", }, }); thisToast.showToast(); return thisToast; } export function remoteLog(e: unknown) { //absolute path and a catch, so the error logger can't itself throw an unhandled rejection while offline fetch("/remote-log", { body: JSON.stringify(e?.toString()), method: "POST", credentials: "same-origin" }).catch( () => {}, ); } //debounce so a burst of failing requests (e.g. many covers loading at once) shows a single notification let lastUnauthorized = 0; //registered by the app root so a 401 anywhere can update the logged-in state let onUnauthorized: (() => void) | undefined; export function setUnauthorizedHandler(handler: () => void) { onUnauthorized = handler; } export function handleUnauthorized(response?: Response | { status?: number } | void): boolean { if (response?.status !== 401) return false; //not debounced: keeps the logged-in state correct even while the toast is throttled onUnauthorized?.(); const now = Date.now(); if (now - lastUnauthorized > 3000) { lastUnauthorized = now; toast("Unauthorized, please sign in", "error"); } return true; } //registered by the app root so a listing the user may not see resets navigation to the top level let onForbiddenPath: (() => void) | undefined; export function setForbiddenPathHandler(handler: () => void) { onForbiddenPath = handler; } export function handleForbiddenPath(response?: Response | { status?: number } | void): boolean { if (response?.status !== 403) return false; onForbiddenPath?.(); toast("That folder is not available to you, returning to the top level", "error"); return true; } export function formatBytes(bytes: number): string { if (bytes === 0) return "Queued..."; const k = 1024; const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; const i = Math.floor(Math.log(bytes) / Math.log(k)); const value = bytes / k ** i; return `${value.toFixed(2)} ${sizes[i]}`; } export function unproxy(value: T): T { return JSON.parse(JSON.stringify(value)); } function getItemName(item: Pick): string; function getItemName(item: Pick | null): string | undefined; function getItemName(item: Pick | null) { if (!item) return undefined; return basename(item.path); } export function formatFilename(file: Omit, format: FileDisplay): string { switch (format) { case FileDisplay.FILENAME: return getItemName(file); case FileDisplay.TITLE: return file.metadata.title || getItemName(file); case FileDisplay.TRACKNO_TITLE: { if (!file.metadata.title) return getItemName(file); const prefix = file.metadata.trackNumber ? `${file.metadata.trackNumber}. ` : ""; return `${prefix}${file.metadata.title}`; } } throw new Error(`unhandled: ${format}`); }