palico-bot/public/scripts/common.js
Shinuwa d14cc414b5
All checks were successful
Deploy Palico Bot / check (push) Successful in 10s
Deploy Palico Bot / deploy (push) Successful in 6s
Fix unreadable dropdowns and tidy the jukebox page on phones
Section dropdowns had a transparent background and white text: Chrome
on Windows drew their options on white, so they could not be read.
Selects and their options now get a solid dark background.

Also style the file picker button and checkboxes, keep the drag-and-drop
badge on one line, and on phones shrink the illustration, lay the player
buttons out on two columns and fit track and section buttons on fewer
lines. Dates are shown in short French ("2 déc. 2026, 11:24").

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

174 lines
5.2 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;
statusElement.className = `status status--${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" });
export function formatDate(value) {
if (!value) return "?";
const date = new Date(value);
return Number.isNaN(date.getTime()) ? String(value) : DATE_FORMAT.format(date);
}
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;
};
}