palico-bot/public/scripts/common.js
Shinuwa 25f22dd363
All checks were successful
Deploy Palico Bot / check (push) Successful in 9s
Deploy Palico Bot / deploy (push) Successful in 7s
Make the jukebox the home page, add seeking and redesign the site
Seeking: the progress bar is now a slider. Releasing it calls
POST /api/player/seek, which restarts ffmpeg at that position and swaps
the audio resource without going through Idle, so the track is neither
finished nor requeued in loop mode.

Structure: the jukebox is served at / and the old home page is gone.
/jukebox/ redirects to / with its query string, and the Discord login
callback now returns to /.

Redesign: a login screen until the visitor is signed in, then an app
layout with a top bar, the library on the left and the player and queue
on the right (sticky, two columns from 1000 px). Small screens get a
mini player while the main one is out of view. Icon buttons, a single
play/pause button, a drop zone for uploads, toast messages and a
refined violet palette with checked contrast. A refused password now
returns to the login screen instead of leaving an empty page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 12:04:03 +01:00

186 lines
5.5 KiB
JavaScript

/**
* @file Outils de la page du jukebox indépendants de son affichage : mémoire du mot de passe et du nom,
* messages d'état, échappement HTML, formats de taille, durée et date, client de l'API.
*
* Utilisé par : public/scripts/jukebox.js.
* Attention : chargé tel quel par le navigateur (module ES, sans compilation). Le texte venu de l'API
* passe par escapeHtml avant d'être inséré en HTML.
*/
const API_KEY_STORAGE_KEY = "palico-api-key";
const DISPLAY_NAME_STORAGE_KEY = "palico-display-name";
// Le stockage peut être indisponible (navigation privée, cookies bloqués) : la page doit
// fonctionner quand même, simplement sans mémoire.
function storageGet(storage, key) {
try {
return storage.getItem(key);
} catch {
return null;
}
}
function storageSet(storage, key, value) {
try {
if (value) {
storage.setItem(key, value);
} else {
storage.removeItem(key);
}
} catch {
// Stockage indisponible.
}
}
export function getStoredApiKey() {
return (
storageGet(sessionStorage, API_KEY_STORAGE_KEY) ||
storageGet(localStorage, API_KEY_STORAGE_KEY) ||
""
);
}
export function isApiKeyRemembered() {
return Boolean(storageGet(localStorage, API_KEY_STORAGE_KEY));
}
// remember : garde la clé sur l'appareil (localStorage) au lieu de l'onglet (sessionStorage).
export function setStoredApiKey(value, { remember = false } = {}) {
storageSet(remember ? localStorage : sessionStorage, API_KEY_STORAGE_KEY, value);
storageSet(remember ? sessionStorage : localStorage, API_KEY_STORAGE_KEY, "");
}
export function getStoredDisplayName() {
return storageGet(localStorage, DISPLAY_NAME_STORAGE_KEY) || "";
}
export function setStoredDisplayName(value) {
storageSet(localStorage, DISPLAY_NAME_STORAGE_KEY, value);
}
export function createStatusManager(statusElement) {
let hideTimeout;
function setStatus(message, type = "info", autoHide = true) {
if (!statusElement) return;
statusElement.textContent = message;
// Le type (info, success, error) passe par un attribut : la classe reste celle de la page.
statusElement.dataset.type = type;
statusElement.hidden = false;
if (autoHide) {
clearTimeout(hideTimeout);
hideTimeout = setTimeout(() => {
statusElement.hidden = true;
}, 5000);
}
}
function clearStatus() {
if (!statusElement) return;
statusElement.hidden = true;
statusElement.textContent = "";
clearTimeout(hideTimeout);
}
return { setStatus, clearStatus };
}
export function escapeHtml(text = "") {
return text
.toString()
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
export function formatBytes(bytes = 0) {
if (!Number(bytes)) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
const index = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / Math.pow(1024, index)).toFixed(1)} ${units[index]}`;
}
// Durée lisible : 3:07, 1:05:09. null si inconnue.
export function formatDuration(seconds) {
const value = Number(seconds);
if (!Number.isFinite(value) || value < 0 || seconds === null) return null;
const total = Math.round(value);
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = String(total % 60).padStart(2, "0");
return hours > 0
? `${hours}:${String(minutes).padStart(2, "0")}:${secs}`
: `${minutes}:${secs}`;
}
// Date courte en français, sans les secondes : « 2 déc. 2026, 11:24 ».
const DATE_FORMAT = new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium", timeStyle: "short" });
// Date seule : « 2 déc. 2026 ».
const DAY_FORMAT = new Intl.DateTimeFormat("fr-FR", { dateStyle: "medium" });
function formatWith(format, value) {
if (!value) return "?";
const date = new Date(value);
return Number.isNaN(date.getTime()) ? String(value) : format.format(date);
}
export function formatDate(value) {
return formatWith(DATE_FORMAT, value);
}
export function formatDay(value) {
return formatWith(DAY_FORMAT, value);
}
export function createApiClient({ getApiKey, basePath = "" } = {}) {
const normalizedBase = (basePath || "").replace(/\/$/, "");
return async function apiFetch(path, options = {}) {
const url = path.startsWith("http")
? path
: `${normalizedBase}${path.startsWith("/") ? "" : "/"}${path}`;
const fetchOptions = {
method: options.method || "GET",
headers: new Headers(options.headers || {}),
};
const apiKey = typeof getApiKey === "function" ? getApiKey() : null;
if (apiKey) {
fetchOptions.headers.set("Authorization", `Bearer ${apiKey}`);
}
if (options.body instanceof FormData) {
fetchOptions.body = options.body;
} else if (options.body) {
if (!fetchOptions.headers.has("Content-Type")) {
fetchOptions.headers.set("Content-Type", "application/json");
}
fetchOptions.body =
typeof options.body === "string" ? options.body : JSON.stringify(options.body);
}
const response = await fetch(url, fetchOptions);
const contentType = response.headers.get("content-type") || "";
let payload = null;
if (contentType.includes("application/json")) {
payload = await response.json();
} else {
payload = await response.text();
}
if (!response.ok) {
const errorMessage = payload?.error || payload?.message || response.statusText;
const error = new Error(errorMessage);
error.status = response.status;
throw error;
}
return payload;
};
}