Headers: - Every JavaScript file (sources, front, scripts, tests) starts with a /** @file … */ header, in the three levels used by sokko-g: a short description for simple files; Utilisé par / Attention / @see for shared modules; a full header (context, entry points, callers, dependencies, pitfalls) for index.js, the music queue, the web server, the storage manager and the jukebox page script. - No @author, @version or @since: git already knows. - test/fileHeaders.test.js fails `npm run check` when a header is missing or a central file's header is incomplete. Stylesheet (no visual change, checked by comparing every element's computed styles in Chromium at 1280, 800 and 400 px, hover included): - Role header and section comments. - Transparent shades derive from the colour variables with color-mix() instead of copied rgba() values; new tokens for repeated values (text, text on accent, accent gradient, white veils, shadow). - Native nesting for buttons, the live indicator, upload rows and home cards; drop the unused .hero__visual--large and redundant rules. - Utility classes move to the end so they win over components. The library list's u-mt-1, which never applied (.list reset it), is removed to keep the layout as it was. Docs: CONTRIBUTING.md describes the language, header and stylesheet conventions; CLAUDE.md points to it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
5 KiB
JavaScript
174 lines
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;
|
|
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, "&")
|
|
.replace(/</g, "<")
|
|
.replace(/>/g, ">")
|
|
.replace(/"/g, """)
|
|
.replace(/'/g, "'");
|
|
}
|
|
|
|
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}`;
|
|
}
|
|
|
|
export function formatDate(value) {
|
|
if (!value) return "?";
|
|
try {
|
|
return new Date(value).toLocaleString();
|
|
} catch (_) {
|
|
return 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;
|
|
};
|
|
}
|