Add section images, larger covers and track tags
Section images:
- A section gets an optional image, set from its new "Modifier" dialog
(name and image), which replaces "Renommer". It goes through the same
conversion as track covers and is deleted with its section.
- Track and section uploads share routes/coverUpload.js. The cover
folder is created again if it went missing, instead of failing.
Larger images: 72 px for tracks (was 48), 96 px for section headers,
160 px in the player and the edit dialog (was 96); smaller on phones.
Tags:
- Library tracks take free tags, edited in the "Modifier" dialog, which
suggests the tags already in use. Case is ignored ("Épique" and
"épique" are one tag); at most 15 tags of 30 characters.
- A tag bar above the library filters it, and the "Tout ajouter"
buttons (global and per section) then only queue its tracks
(enqueue-all takes a tag). The search also matches tags.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
793765fb79
commit
bda95ca946
13 changed files with 601 additions and 165 deletions
15
README.md
15
README.md
|
|
@ -105,11 +105,16 @@ file d'attente.
|
||||||
- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et
|
- Chaque morceau passe par `ffmpeg`, qui normalise le volume (EBU R128) et
|
||||||
encode en Opus : Discord reçoit l'audio sans réencodage.
|
encode en Opus : Discord reçoit l'audio sans réencodage.
|
||||||
- La page web range la bibliothèque en sections (chacune peut être ajoutée à
|
- La page web range la bibliothèque en sections (chacune peut être ajoutée à
|
||||||
la file d'un coup, mélangée ou non) et donne une pochette à chaque morceau :
|
la file d'un coup, mélangée ou non) et donne une image à chaque section et
|
||||||
celle intégrée au fichier est reprise à l'ajout, et le bouton « Modifier »
|
une pochette à chaque morceau : celle intégrée au fichier est reprise à
|
||||||
permet d'en envoyer une autre (PNG, JPEG, WebP ou GIF), réduite en JPEG de
|
l'ajout, et le bouton « Modifier » permet d'en envoyer une autre (PNG, JPEG,
|
||||||
512 px. Les pochettes sont servies sous `/covers/` sans authentification,
|
WebP ou GIF), réduite en JPEG de 512 px. Images et pochettes sont servies
|
||||||
sous des noms aléatoires que seule l'API donne.
|
sous `/covers/` sans authentification, sous des noms aléatoires que seule
|
||||||
|
l'API donne.
|
||||||
|
- Les morceaux de la bibliothèque peuvent recevoir des étiquettes libres
|
||||||
|
(« épique », « calme »…), sans distinction de majuscules. Choisir une
|
||||||
|
étiquette au-dessus de la liste filtre la bibliothèque, et les boutons
|
||||||
|
« Tout ajouter » n'ajoutent alors que ses morceaux.
|
||||||
|
|
||||||
- La file est enregistrée dans `storage/runtime/queue.json` : après un
|
- La file est enregistrée dans `storage/runtime/queue.json` : après un
|
||||||
redémarrage, elle reprend dès que quelqu'un est dans le salon vocal.
|
redémarrage, elle reprend dès que quelqu'un est dans le salon vocal.
|
||||||
|
|
|
||||||
|
|
@ -169,7 +169,7 @@
|
||||||
<h2 id="libraryTitle">Bibliothèque permanente</h2>
|
<h2 id="libraryTitle">Bibliothèque permanente</h2>
|
||||||
<p class="panel__subtitle">
|
<p class="panel__subtitle">
|
||||||
Les fichiers conservés sont listés ici. Range-les en sections,
|
Les fichiers conservés sont listés ici. Range-les en sections,
|
||||||
donne-leur une pochette, ajoute-les à la file.
|
donne-leur une image, ajoute-les à la file.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="toolbar">
|
<div class="toolbar">
|
||||||
|
|
@ -184,38 +184,48 @@
|
||||||
<input
|
<input
|
||||||
type="search"
|
type="search"
|
||||||
id="librarySearch"
|
id="librarySearch"
|
||||||
placeholder="Rechercher un morceau…"
|
placeholder="Rechercher un morceau ou une étiquette…"
|
||||||
autocomplete="off"
|
autocomplete="off"
|
||||||
/>
|
/>
|
||||||
|
<div id="libraryTags" class="tag-list tag-list--filter" role="group" aria-label="Filtrer par étiquette" hidden></div>
|
||||||
<div id="libraryList" class="library"></div>
|
<div id="libraryList" class="library"></div>
|
||||||
<p id="libraryEmpty" class="text--muted">Aucun fichier permanent enregistré.</p>
|
<p id="libraryEmpty" class="text--muted">Aucun fichier permanent enregistré.</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<dialog id="trackDialog" class="dialog" aria-labelledby="trackDialogTitle">
|
<dialog id="editDialog" class="dialog" aria-labelledby="editDialogTitle">
|
||||||
<form id="trackForm">
|
<form id="editForm">
|
||||||
<h2 id="trackDialogTitle">Modifier le morceau</h2>
|
<h2 id="editDialogTitle">Modifier le morceau</h2>
|
||||||
|
|
||||||
<div class="track-editor">
|
<div class="cover-editor">
|
||||||
<div id="trackCoverPreview" class="cover cover--large cover--empty" aria-hidden="true"></div>
|
<div id="editCoverPreview" class="cover cover--large cover--empty" aria-hidden="true"></div>
|
||||||
<div class="track-editor__cover-fields">
|
<div class="cover-editor__fields">
|
||||||
<label for="trackCoverInput">Pochette</label>
|
<label id="editCoverLabel" for="editCoverInput">Pochette</label>
|
||||||
<input type="file" id="trackCoverInput" accept="image/png,image/jpeg,image/webp,image/gif" />
|
<input type="file" id="editCoverInput" accept="image/png,image/jpeg,image/webp,image/gif" />
|
||||||
<p class="hint">PNG, JPEG, WebP ou GIF, 10 Mo au plus. Recadrée à 512 px.</p>
|
<p class="hint">PNG, JPEG, WebP ou GIF, 10 Mo au plus. Réduite à 512 px.</p>
|
||||||
<button id="trackCoverRemoveBtn" class="btn btn--ghost btn--small u-mt-1" type="button">
|
<button id="editCoverRemoveBtn" class="btn btn--ghost btn--small u-mt-1" type="button">
|
||||||
Retirer la pochette
|
Retirer la pochette
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<label for="trackTitleInput" class="u-mt-1">Titre</label>
|
<label id="editNameLabel" for="editNameInput" class="u-mt-1">Titre</label>
|
||||||
<input type="text" id="trackTitleInput" maxlength="200" required />
|
<input type="text" id="editNameInput" maxlength="200" required />
|
||||||
|
|
||||||
<label for="trackSectionSelect" class="u-mt-1">Section</label>
|
<div id="editSectionField">
|
||||||
<select id="trackSectionSelect"></select>
|
<label for="editSectionSelect" class="u-mt-1">Section</label>
|
||||||
|
<select id="editSectionSelect"></select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="editTagsField">
|
||||||
|
<label for="editTagsInput" class="u-mt-1">Étiquettes</label>
|
||||||
|
<input type="text" id="editTagsInput" maxlength="500" autocomplete="off" placeholder="épique, calme, combat…" />
|
||||||
|
<p class="hint">Sépare-les par des virgules. Clique sur une étiquette existante pour l'ajouter.</p>
|
||||||
|
<div id="editTagSuggestions" class="tag-list"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="form-actions toolbar">
|
<div class="form-actions toolbar">
|
||||||
<button id="trackCancelBtn" class="btn btn--ghost" type="button">Annuler</button>
|
<button id="editCancelBtn" class="btn btn--ghost" type="button">Annuler</button>
|
||||||
<button id="trackSaveBtn" class="btn" type="submit">Enregistrer</button>
|
<button id="editSaveBtn" class="btn" type="submit">Enregistrer</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,8 @@
|
||||||
* - Tout texte venu de l'API passe par escapeHtml avant d'aller dans innerHTML.
|
* - Tout texte venu de l'API passe par escapeHtml avant d'aller dans innerHTML.
|
||||||
* - Les morceaux de la file n'ont pas de pochette : elle est prise sur leur morceau de bibliothèque
|
* - Les morceaux de la file n'ont pas de pochette : elle est prise sur leur morceau de bibliothèque
|
||||||
* (libraryTrackId), d'où le nouvel affichage de la file à chaque changement de la bibliothèque.
|
* (libraryTrackId), d'où le nouvel affichage de la file à chaque changement de la bibliothèque.
|
||||||
|
* - Le filtre par étiquette (state.activeTag) vaut aussi pour les boutons « Tout ajouter » : seuls
|
||||||
|
* les morceaux affichés partent dans la file. La recherche, elle, n'agit que sur l'affichage.
|
||||||
* - L'aperçu d'une pochette choisie passe par une URL data: ; la politique de sécurité des contenus
|
* - L'aperçu d'une pochette choisie passe par une URL data: ; la politique de sécurité des contenus
|
||||||
* (helmet) refuse les URL blob:.
|
* (helmet) refuse les URL blob:.
|
||||||
* @see README.md#jukebox
|
* @see README.md#jukebox
|
||||||
|
|
@ -52,6 +54,8 @@ const state = {
|
||||||
sections: [],
|
sections: [],
|
||||||
// Sections repliées par la personne ("" : les morceaux sans section).
|
// Sections repliées par la personne ("" : les morceaux sans section).
|
||||||
collapsedSections: new Set(),
|
collapsedSections: new Set(),
|
||||||
|
// Étiquette choisie pour filtrer la bibliothèque, ou null.
|
||||||
|
activeTag: null,
|
||||||
status: "idle",
|
status: "idle",
|
||||||
loop: false,
|
loop: false,
|
||||||
// Position du morceau en cours (ms) au moment où l'état a été reçu.
|
// Position du morceau en cours (ms) au moment où l'état a été reçu.
|
||||||
|
|
@ -89,6 +93,7 @@ const elements = {
|
||||||
libraryList: $("libraryList"),
|
libraryList: $("libraryList"),
|
||||||
libraryEmpty: $("libraryEmpty"),
|
libraryEmpty: $("libraryEmpty"),
|
||||||
librarySearch: $("librarySearch"),
|
librarySearch: $("librarySearch"),
|
||||||
|
libraryTags: $("libraryTags"),
|
||||||
newSectionBtn: $("newSectionBtn"),
|
newSectionBtn: $("newSectionBtn"),
|
||||||
enqueueAllBtn: $("enqueueAllBtn"),
|
enqueueAllBtn: $("enqueueAllBtn"),
|
||||||
enqueueAllShuffledBtn: $("enqueueAllShuffledBtn"),
|
enqueueAllShuffledBtn: $("enqueueAllShuffledBtn"),
|
||||||
|
|
@ -108,15 +113,22 @@ const elements = {
|
||||||
heroUploadBtn: $("heroUploadBtn"),
|
heroUploadBtn: $("heroUploadBtn"),
|
||||||
heroQueueBtn: $("heroQueueBtn"),
|
heroQueueBtn: $("heroQueueBtn"),
|
||||||
queueSection: $("queueSection"),
|
queueSection: $("queueSection"),
|
||||||
trackDialog: $("trackDialog"),
|
editDialog: $("editDialog"),
|
||||||
trackForm: $("trackForm"),
|
editDialogTitle: $("editDialogTitle"),
|
||||||
trackCoverPreview: $("trackCoverPreview"),
|
editForm: $("editForm"),
|
||||||
trackCoverInput: $("trackCoverInput"),
|
editCoverPreview: $("editCoverPreview"),
|
||||||
trackCoverRemoveBtn: $("trackCoverRemoveBtn"),
|
editCoverLabel: $("editCoverLabel"),
|
||||||
trackTitleInput: $("trackTitleInput"),
|
editCoverInput: $("editCoverInput"),
|
||||||
trackSectionSelect: $("trackSectionSelect"),
|
editCoverRemoveBtn: $("editCoverRemoveBtn"),
|
||||||
trackCancelBtn: $("trackCancelBtn"),
|
editNameLabel: $("editNameLabel"),
|
||||||
trackSaveBtn: $("trackSaveBtn"),
|
editNameInput: $("editNameInput"),
|
||||||
|
editSectionField: $("editSectionField"),
|
||||||
|
editSectionSelect: $("editSectionSelect"),
|
||||||
|
editTagsField: $("editTagsField"),
|
||||||
|
editTagsInput: $("editTagsInput"),
|
||||||
|
editTagSuggestions: $("editTagSuggestions"),
|
||||||
|
editCancelBtn: $("editCancelBtn"),
|
||||||
|
editSaveBtn: $("editSaveBtn"),
|
||||||
};
|
};
|
||||||
|
|
||||||
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
const { setStatus, clearStatus } = createStatusManager(elements.status);
|
||||||
|
|
@ -423,22 +435,86 @@ function libraryGroups() {
|
||||||
return [...groups, unsorted];
|
return [...groups, unsorted];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Étiquettes : « Calme » et « calme » sont la même (comme sur le serveur, features/tags.js).
|
||||||
|
const tagKey = (tag) => tag.toLocaleLowerCase("fr");
|
||||||
|
const trackHasTag = (track, tag) => (track.tags ?? []).some((item) => tagKey(item) === tagKey(tag));
|
||||||
|
|
||||||
|
// Étiquettes de la bibliothèque, par ordre alphabétique, avec leur nombre de morceaux.
|
||||||
|
function libraryTags() {
|
||||||
|
const tags = new Map();
|
||||||
|
for (const track of state.library) {
|
||||||
|
for (const tag of track.tags ?? []) {
|
||||||
|
const entry = tags.get(tagKey(tag)) ?? { label: tag, count: 0 };
|
||||||
|
entry.count += 1;
|
||||||
|
tags.set(tagKey(tag), entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...tags.values()].sort((a, b) => a.label.localeCompare(b.label, "fr"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function setActiveTag(tag) {
|
||||||
|
state.activeTag = tag && state.activeTag && tagKey(tag) === tagKey(state.activeTag) ? null : tag;
|
||||||
|
renderLibrary();
|
||||||
|
}
|
||||||
|
|
||||||
|
function tagButton(tag, { pressed = false, count } = {}) {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.className = "tag";
|
||||||
|
button.textContent = tag;
|
||||||
|
if (count !== undefined) {
|
||||||
|
const badge = document.createElement("span");
|
||||||
|
badge.className = "tag__count";
|
||||||
|
badge.textContent = String(count);
|
||||||
|
button.append(badge);
|
||||||
|
}
|
||||||
|
button.setAttribute("aria-pressed", String(pressed));
|
||||||
|
button.addEventListener("click", () => setActiveTag(tag));
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTagFilter() {
|
||||||
|
const tags = libraryTags();
|
||||||
|
if (state.activeTag && !tags.some(({ label }) => tagKey(label) === tagKey(state.activeTag))) {
|
||||||
|
state.activeTag = null;
|
||||||
|
}
|
||||||
|
elements.libraryTags.hidden = tags.length === 0;
|
||||||
|
elements.libraryTags.replaceChildren(
|
||||||
|
...tags.map(({ label, count }) =>
|
||||||
|
tagButton(label, {
|
||||||
|
count,
|
||||||
|
pressed: Boolean(state.activeTag) && tagKey(label) === tagKey(state.activeTag),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function renderLibrary() {
|
function renderLibrary() {
|
||||||
|
renderTagFilter();
|
||||||
const query = elements.librarySearch.value.trim().toLowerCase();
|
const query = elements.librarySearch.value.trim().toLowerCase();
|
||||||
|
const tag = state.activeTag;
|
||||||
const matches = (track) =>
|
const matches = (track) =>
|
||||||
`${track.title || ""} ${track.originalName || ""} ${track.artist || ""}`
|
(!tag || trackHasTag(track, tag)) &&
|
||||||
|
`${track.title || ""} ${track.originalName || ""} ${track.artist || ""} ${(track.tags ?? []).join(" ")}`
|
||||||
.toLowerCase()
|
.toLowerCase()
|
||||||
.includes(query);
|
.includes(query);
|
||||||
const matchCount = state.library.filter(matches).length;
|
const matchCount = state.library.filter(matches).length;
|
||||||
|
const filtering = Boolean(query || tag);
|
||||||
|
|
||||||
elements.libraryList.replaceChildren();
|
elements.libraryList.replaceChildren();
|
||||||
const isEmpty = state.library.length === 0 && state.sections.length === 0;
|
const isEmpty = state.library.length === 0 && state.sections.length === 0;
|
||||||
elements.libraryEmpty.hidden = !isEmpty && (matchCount > 0 || !query);
|
elements.libraryEmpty.hidden = !isEmpty && (matchCount > 0 || !filtering);
|
||||||
elements.libraryEmpty.textContent = isEmpty
|
elements.libraryEmpty.textContent = isEmpty
|
||||||
? "Aucun fichier permanent enregistré."
|
? "Aucun fichier permanent enregistré."
|
||||||
: "Aucun morceau ne correspond à la recherche.";
|
: "Aucun morceau ne correspond à la recherche.";
|
||||||
elements.enqueueAllBtn.disabled = state.library.length === 0;
|
// Avec une étiquette choisie, les boutons n'ajoutent que ses morceaux.
|
||||||
elements.enqueueAllShuffledBtn.disabled = state.library.length === 0;
|
const taggedCount = tag ? state.library.filter((track) => trackHasTag(track, tag)).length : 0;
|
||||||
|
elements.enqueueAllBtn.textContent = tag ? `Ajouter « ${tag} »` : "Tout ajouter";
|
||||||
|
elements.enqueueAllShuffledBtn.textContent = tag
|
||||||
|
? `Ajouter « ${tag} », mélangé`
|
||||||
|
: "Tout ajouter, mélangé";
|
||||||
|
elements.enqueueAllBtn.disabled = (tag ? taggedCount : state.library.length) === 0;
|
||||||
|
elements.enqueueAllShuffledBtn.disabled = elements.enqueueAllBtn.disabled;
|
||||||
|
|
||||||
// Sans section créée, la bibliothèque reste une simple liste.
|
// Sans section créée, la bibliothèque reste une simple liste.
|
||||||
if (state.sections.length === 0) {
|
if (state.sections.length === 0) {
|
||||||
|
|
@ -449,12 +525,12 @@ function renderLibrary() {
|
||||||
const groups = libraryGroups();
|
const groups = libraryGroups();
|
||||||
groups.forEach((group, index) => {
|
groups.forEach((group, index) => {
|
||||||
const shown = group.tracks.filter(matches);
|
const shown = group.tracks.filter(matches);
|
||||||
if (shown.length === 0 && (query || !group.section)) return;
|
if (shown.length === 0 && (filtering || !group.section)) return;
|
||||||
elements.libraryList.append(
|
elements.libraryList.append(
|
||||||
renderSection(group, shown, {
|
renderSection(group, shown, {
|
||||||
index,
|
index,
|
||||||
last: state.sections.length - 1,
|
last: state.sections.length - 1,
|
||||||
searching: Boolean(query),
|
searching: filtering,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
@ -473,12 +549,19 @@ function renderSection({ section, tracks }, shown, { index, last, searching }) {
|
||||||
|
|
||||||
const total = tracks.reduce((sum, track) => sum + (track.duration || 0), 0);
|
const total = tracks.reduce((sum, track) => sum + (track.duration || 0), 0);
|
||||||
const count = searching ? `${shown.length} sur ${tracks.length}` : String(tracks.length);
|
const count = searching ? `${shown.length} sur ${tracks.length}` : String(tracks.length);
|
||||||
const disabledIfEmpty = tracks.length === 0 ? "disabled" : "";
|
// Avec une étiquette choisie, « Tout ajouter » n'ajoute que les morceaux qui la portent.
|
||||||
|
const addable = state.activeTag
|
||||||
|
? tracks.filter((track) => trackHasTag(track, state.activeTag)).length
|
||||||
|
: tracks.length;
|
||||||
|
const disabledIfEmpty = addable === 0 ? "disabled" : "";
|
||||||
details.innerHTML = `
|
details.innerHTML = `
|
||||||
<summary class="library-section__summary">
|
<summary class="library-section__summary">
|
||||||
<span class="library-section__name">${escapeHtml(section?.name ?? "Sans section")}</span>
|
${section?.coverUrl ? `<img class="cover cover--section" src="${escapeHtml(section.coverUrl)}" alt="" loading="lazy" />` : ""}
|
||||||
<span class="library-section__count">
|
<span class="library-section__heading">
|
||||||
${count} morceau(x)${total ? ` • ${formatDuration(total)}` : ""}
|
<span class="library-section__name">${escapeHtml(section?.name ?? "Sans section")}</span>
|
||||||
|
<span class="library-section__count">
|
||||||
|
${count} morceau(x)${total ? ` • ${formatDuration(total)}` : ""}
|
||||||
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</summary>
|
</summary>
|
||||||
<div class="library-section__toolbar toolbar">
|
<div class="library-section__toolbar toolbar">
|
||||||
|
|
@ -486,7 +569,7 @@ function renderSection({ section, tracks }, shown, { index, last, searching }) {
|
||||||
<button class="btn btn--secondary btn--small" type="button" data-action="shuffle" ${disabledIfEmpty}>Mélangé</button>
|
<button class="btn btn--secondary btn--small" type="button" data-action="shuffle" ${disabledIfEmpty}>Mélangé</button>
|
||||||
${
|
${
|
||||||
section
|
section
|
||||||
? `<button class="btn btn--secondary btn--small" type="button" data-action="rename">Renommer</button>
|
? `<button class="btn btn--secondary btn--small" type="button" data-action="edit">Modifier</button>
|
||||||
<button class="btn btn--secondary btn--small" type="button" data-action="up" aria-label="Monter la section" title="Monter" ${index === 0 ? "disabled" : ""}>▲</button>
|
<button class="btn btn--secondary btn--small" type="button" data-action="up" aria-label="Monter la section" title="Monter" ${index === 0 ? "disabled" : ""}>▲</button>
|
||||||
<button class="btn btn--secondary btn--small" type="button" data-action="down" aria-label="Descendre la section" title="Descendre" ${index === last ? "disabled" : ""}>▼</button>
|
<button class="btn btn--secondary btn--small" type="button" data-action="down" aria-label="Descendre la section" title="Descendre" ${index === last ? "disabled" : ""}>▼</button>
|
||||||
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>`
|
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>`
|
||||||
|
|
@ -525,6 +608,7 @@ function renderTrackList(tracks) {
|
||||||
<div class="media-item__meta">
|
<div class="media-item__meta">
|
||||||
${duration ? `${duration} • ` : ""}${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
|
${duration ? `${duration} • ` : ""}${formatBytes(track.size)} • Ajouté le ${formatDate(track.createdAt)}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="tag-list"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="media-item__actions">
|
<div class="media-item__actions">
|
||||||
<button class="btn btn--small" type="button" data-action="enqueue">Ajouter</button>
|
<button class="btn btn--small" type="button" data-action="enqueue">Ajouter</button>
|
||||||
|
|
@ -532,11 +616,18 @@ function renderTrackList(tracks) {
|
||||||
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>
|
<button class="btn btn--danger btn--small" type="button" data-action="delete">Supprimer</button>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
li.querySelectorAll("button").forEach((button) => {
|
li.querySelectorAll(".media-item__actions button").forEach((button) => {
|
||||||
button.addEventListener("click", () =>
|
button.addEventListener("click", () =>
|
||||||
handleLibraryAction(button.dataset.action, track, button)
|
handleLibraryAction(button.dataset.action, track, button)
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
li.querySelector(".tag-list").append(
|
||||||
|
...(track.tags ?? []).map((tag) =>
|
||||||
|
tagButton(tag, {
|
||||||
|
pressed: Boolean(state.activeTag) && tagKey(tag) === tagKey(state.activeTag),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
list.append(li);
|
list.append(li);
|
||||||
}
|
}
|
||||||
return list;
|
return list;
|
||||||
|
|
@ -544,7 +635,7 @@ function renderTrackList(tracks) {
|
||||||
|
|
||||||
// Listes de sections du formulaire d'ajout et de la fenêtre de modification.
|
// Listes de sections du formulaire d'ajout et de la fenêtre de modification.
|
||||||
function renderSectionChoices() {
|
function renderSectionChoices() {
|
||||||
for (const select of [elements.uploadSectionSelect, elements.trackSectionSelect]) {
|
for (const select of [elements.uploadSectionSelect, elements.editSectionSelect]) {
|
||||||
const selected = select.value;
|
const selected = select.value;
|
||||||
select.replaceChildren(new Option("Sans section", ""));
|
select.replaceChildren(new Option("Sans section", ""));
|
||||||
for (const section of state.sections) {
|
for (const section of state.sections) {
|
||||||
|
|
@ -625,7 +716,7 @@ async function handleLibraryAction(action, track, button) {
|
||||||
);
|
);
|
||||||
setStatus(`« ${track.title || track.originalName} » ajouté à la file`, "success");
|
setStatus(`« ${track.title || track.originalName} » ajouté à la file`, "success");
|
||||||
} else if (action === "edit") {
|
} else if (action === "edit") {
|
||||||
openTrackEditor(track);
|
openEditor("track", track);
|
||||||
return;
|
return;
|
||||||
} else if (action === "delete") {
|
} else if (action === "delete") {
|
||||||
if (!confirm(`Supprimer « ${track.title || track.originalName} » de la bibliothèque ?`)) {
|
if (!confirm(`Supprimer « ${track.title || track.originalName} » de la bibliothèque ?`)) {
|
||||||
|
|
@ -648,7 +739,7 @@ async function enqueueAll(shuffle, button, sectionId) {
|
||||||
const { tracks } = await withBusyButton(button, () =>
|
const { tracks } = await withBusyButton(button, () =>
|
||||||
apiFetch("/library/enqueue-all", {
|
apiFetch("/library/enqueue-all", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: { shuffle, sectionId, requestedBy: requesterName() },
|
body: { shuffle, sectionId, tag: state.activeTag ?? undefined, requestedBy: requesterName() },
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
setStatus(`${tracks.length} morceau(x) ajouté(s) à la file`, "success");
|
setStatus(`${tracks.length} morceau(x) ajouté(s) à la file`, "success");
|
||||||
|
|
@ -678,16 +769,11 @@ async function handleSectionAction(action, section, index, button) {
|
||||||
await enqueueAll(action === "shuffle", button, section?.id ?? null);
|
await enqueueAll(action === "shuffle", button, section?.id ?? null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (action === "rename") {
|
if (action === "edit") {
|
||||||
const name = prompt("Nouveau nom de la section", section.name);
|
openEditor("section", section);
|
||||||
if (!name || !name.trim()) return;
|
return;
|
||||||
await withBusyButton(button, () =>
|
}
|
||||||
apiFetch(`/library/sections/${section.id}`, {
|
if (action === "up" || action === "down") {
|
||||||
method: "PATCH",
|
|
||||||
body: { name: name.trim() },
|
|
||||||
})
|
|
||||||
);
|
|
||||||
} else if (action === "up" || action === "down") {
|
|
||||||
const position = index + (action === "up" ? -1 : 1);
|
const position = index + (action === "up" ? -1 : 1);
|
||||||
await withBusyButton(button, () =>
|
await withBusyButton(button, () =>
|
||||||
apiFetch(`/library/sections/${section.id}`, { method: "PATCH", body: { position } })
|
apiFetch(`/library/sections/${section.id}`, { method: "PATCH", body: { position } })
|
||||||
|
|
@ -711,80 +797,132 @@ async function handleSectionAction(action, section, index, button) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// Fenêtre de modification d'un morceau (titre, section, pochette)
|
// Fenêtre de modification : morceau (titre, section, pochette) ou section (nom, image)
|
||||||
|
|
||||||
const MAX_COVER_SIZE = 10 * 1024 * 1024;
|
const MAX_COVER_SIZE = 10 * 1024 * 1024;
|
||||||
let editedTrack = null;
|
// { kind: "track" | "section", item } pendant que la fenêtre est ouverte.
|
||||||
|
let editing = null;
|
||||||
let removeCover = false;
|
let removeCover = false;
|
||||||
|
|
||||||
function showCoverPreview(url) {
|
function showCoverPreview(url) {
|
||||||
const preview = elements.trackCoverPreview;
|
const preview = elements.editCoverPreview;
|
||||||
preview.classList.toggle("cover--empty", !url);
|
preview.classList.toggle("cover--empty", !url);
|
||||||
preview.style.backgroundImage = url ? `url("${url}")` : "";
|
preview.style.backgroundImage = url ? `url("${url}")` : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function openTrackEditor(track) {
|
function openEditor(kind, item) {
|
||||||
editedTrack = track;
|
const isTrack = kind === "track";
|
||||||
|
editing = { kind, item };
|
||||||
removeCover = false;
|
removeCover = false;
|
||||||
elements.trackTitleInput.value = track.title || track.originalName;
|
elements.editDialogTitle.textContent = isTrack ? "Modifier le morceau" : "Modifier la section";
|
||||||
renderSectionChoices();
|
elements.editCoverLabel.textContent = isTrack ? "Pochette" : "Image";
|
||||||
elements.trackSectionSelect.value = track.sectionId ?? "";
|
elements.editCoverRemoveBtn.textContent = isTrack ? "Retirer la pochette" : "Retirer l'image";
|
||||||
elements.trackCoverInput.value = "";
|
elements.editNameLabel.textContent = isTrack ? "Titre" : "Nom";
|
||||||
elements.trackCoverRemoveBtn.hidden = !track.coverUrl;
|
elements.editNameInput.maxLength = isTrack ? 200 : 80;
|
||||||
showCoverPreview(track.coverUrl);
|
elements.editNameInput.value = isTrack ? item.title || item.originalName : item.name;
|
||||||
elements.trackDialog.showModal();
|
elements.editSectionField.hidden = !isTrack;
|
||||||
|
elements.editTagsField.hidden = !isTrack;
|
||||||
|
if (isTrack) {
|
||||||
|
renderSectionChoices();
|
||||||
|
elements.editSectionSelect.value = item.sectionId ?? "";
|
||||||
|
elements.editTagsInput.value = (item.tags ?? []).join(", ");
|
||||||
|
renderTagSuggestions();
|
||||||
|
}
|
||||||
|
elements.editCoverInput.value = "";
|
||||||
|
elements.editCoverRemoveBtn.hidden = !item.coverUrl;
|
||||||
|
showCoverPreview(item.coverUrl);
|
||||||
|
elements.editDialog.showModal();
|
||||||
}
|
}
|
||||||
|
|
||||||
function previewChosenCover() {
|
function previewChosenCover() {
|
||||||
const file = elements.trackCoverInput.files[0];
|
const file = elements.editCoverInput.files[0];
|
||||||
if (!file) {
|
if (!file) {
|
||||||
showCoverPreview(removeCover ? null : editedTrack?.coverUrl);
|
showCoverPreview(removeCover ? null : editing?.item.coverUrl);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (file.size > MAX_COVER_SIZE) {
|
if (file.size > MAX_COVER_SIZE) {
|
||||||
setStatus("Image trop lourde : 10 Mo au plus", "error");
|
setStatus("Image trop lourde : 10 Mo au plus", "error");
|
||||||
elements.trackCoverInput.value = "";
|
elements.editCoverInput.value = "";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.addEventListener("load", () => showCoverPreview(reader.result));
|
reader.addEventListener("load", () => showCoverPreview(reader.result));
|
||||||
reader.readAsDataURL(file);
|
reader.readAsDataURL(file);
|
||||||
elements.trackCoverRemoveBtn.hidden = false;
|
elements.editCoverRemoveBtn.hidden = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearChosenCover() {
|
function clearChosenCover() {
|
||||||
removeCover = true;
|
removeCover = true;
|
||||||
elements.trackCoverInput.value = "";
|
elements.editCoverInput.value = "";
|
||||||
elements.trackCoverRemoveBtn.hidden = true;
|
elements.editCoverRemoveBtn.hidden = true;
|
||||||
showCoverPreview(null);
|
showCoverPreview(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveTrackEditor(event) {
|
// Étiquettes tapées dans la fenêtre, séparées par des virgules.
|
||||||
event.preventDefault();
|
function typedTags() {
|
||||||
const track = editedTrack;
|
return elements.editTagsInput.value
|
||||||
if (!track) return;
|
.split(",")
|
||||||
|
.map((tag) => tag.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Étiquettes déjà utilisées dans la bibliothèque et pas encore tapées : un clic les ajoute.
|
||||||
|
function renderTagSuggestions() {
|
||||||
|
const typed = new Set(typedTags().map(tagKey));
|
||||||
|
const suggestions = libraryTags().filter(({ label }) => !typed.has(tagKey(label)));
|
||||||
|
elements.editTagSuggestions.replaceChildren(
|
||||||
|
...suggestions.map(({ label }) => {
|
||||||
|
const button = document.createElement("button");
|
||||||
|
button.type = "button";
|
||||||
|
button.className = "tag";
|
||||||
|
button.textContent = `+ ${label}`;
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
elements.editTagsInput.value = [...typedTags(), label].join(", ");
|
||||||
|
renderTagSuggestions();
|
||||||
|
});
|
||||||
|
return button;
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Changements de texte à envoyer : titre, section et étiquettes d'un morceau, nom d'une section.
|
||||||
|
function editorChanges({ kind, item }) {
|
||||||
const changes = {};
|
const changes = {};
|
||||||
const title = elements.trackTitleInput.value.trim();
|
const name = elements.editNameInput.value.trim();
|
||||||
if (title && title !== (track.title || track.originalName)) changes.title = title;
|
if (kind === "section") {
|
||||||
const sectionId = elements.trackSectionSelect.value || null;
|
if (name && name !== item.name) changes.name = name;
|
||||||
if (sectionId !== (track.sectionId ?? null)) changes.sectionId = sectionId;
|
return changes;
|
||||||
const coverFile = elements.trackCoverInput.files[0];
|
}
|
||||||
|
if (name && name !== (item.title || item.originalName)) changes.title = name;
|
||||||
|
const sectionId = elements.editSectionSelect.value || null;
|
||||||
|
if (sectionId !== (item.sectionId ?? null)) changes.sectionId = sectionId;
|
||||||
|
const tags = typedTags();
|
||||||
|
if (tags.join("\n") !== (item.tags ?? []).join("\n")) changes.tags = tags;
|
||||||
|
return changes;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveEditor(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!editing) return;
|
||||||
|
const { kind, item } = editing;
|
||||||
|
const path = kind === "track" ? `/library/${item.id}` : `/library/sections/${item.id}`;
|
||||||
|
const changes = editorChanges(editing);
|
||||||
|
const coverFile = elements.editCoverInput.files[0];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await withBusyButton(elements.trackSaveBtn, async () => {
|
await withBusyButton(elements.editSaveBtn, async () => {
|
||||||
if (Object.keys(changes).length > 0) {
|
if (Object.keys(changes).length > 0) {
|
||||||
await apiFetch(`/library/${track.id}`, { method: "PATCH", body: changes });
|
await apiFetch(path, { method: "PATCH", body: changes });
|
||||||
}
|
}
|
||||||
if (coverFile) {
|
if (coverFile) {
|
||||||
const data = new FormData();
|
const data = new FormData();
|
||||||
data.append("cover", coverFile);
|
data.append("cover", coverFile);
|
||||||
await apiFetch(`/library/${track.id}/cover`, { method: "PUT", body: data });
|
await apiFetch(`${path}/cover`, { method: "PUT", body: data });
|
||||||
} else if (removeCover && track.coverUrl) {
|
} else if (removeCover && item.coverUrl) {
|
||||||
await apiFetch(`/library/${track.id}/cover`, { method: "DELETE" });
|
await apiFetch(`${path}/cover`, { method: "DELETE" });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
elements.trackDialog.close();
|
elements.editDialog.close();
|
||||||
if (!state.live) await refreshLibrary();
|
if (!state.live) await refreshLibrary();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// La fenêtre reste ouverte : la personne peut corriger (autre image…) et réessayer.
|
// La fenêtre reste ouverte : la personne peut corriger (autre image…) et réessayer.
|
||||||
|
|
@ -1019,12 +1157,13 @@ function bindEvents() {
|
||||||
elements.newSectionBtn.addEventListener("click", () => createSection(elements.newSectionBtn));
|
elements.newSectionBtn.addEventListener("click", () => createSection(elements.newSectionBtn));
|
||||||
elements.permanentCheckbox.addEventListener("change", renderSectionChoices);
|
elements.permanentCheckbox.addEventListener("change", renderSectionChoices);
|
||||||
|
|
||||||
elements.trackForm.addEventListener("submit", saveTrackEditor);
|
elements.editForm.addEventListener("submit", saveEditor);
|
||||||
elements.trackCancelBtn.addEventListener("click", () => elements.trackDialog.close());
|
elements.editCancelBtn.addEventListener("click", () => elements.editDialog.close());
|
||||||
elements.trackCoverInput.addEventListener("change", previewChosenCover);
|
elements.editCoverInput.addEventListener("change", previewChosenCover);
|
||||||
elements.trackCoverRemoveBtn.addEventListener("click", clearChosenCover);
|
elements.editTagsInput.addEventListener("input", renderTagSuggestions);
|
||||||
elements.trackDialog.addEventListener("close", () => {
|
elements.editCoverRemoveBtn.addEventListener("click", clearChosenCover);
|
||||||
editedTrack = null;
|
elements.editDialog.addEventListener("close", () => {
|
||||||
|
editing = null;
|
||||||
});
|
});
|
||||||
elements.enqueueAllBtn.addEventListener("click", () =>
|
elements.enqueueAllBtn.addEventListener("click", () =>
|
||||||
enqueueAll(false, elements.enqueueAllBtn)
|
enqueueAll(false, elements.enqueueAllBtn)
|
||||||
|
|
|
||||||
|
|
@ -597,18 +597,19 @@ a.btn {
|
||||||
/* Pochette d'un morceau : <img>, ou <div> vide (note de musique) ou à image de fond (aperçu). */
|
/* Pochette d'un morceau : <img>, ou <div> vide (note de musique) ou à image de fond (aperçu). */
|
||||||
.cover {
|
.cover {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
width: 48px;
|
width: 72px;
|
||||||
height: 48px;
|
height: 72px;
|
||||||
border-radius: 10px;
|
border-radius: 12px;
|
||||||
object-fit: cover;
|
object-fit: cover;
|
||||||
background: var(--surface-soft) center / cover no-repeat;
|
background: var(--surface-soft) center / cover no-repeat;
|
||||||
border: 1px solid var(--border);
|
border: 1px solid var(--border);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Lecteur et fenêtre de modification. */
|
||||||
.cover--large {
|
.cover--large {
|
||||||
width: 96px;
|
width: 160px;
|
||||||
height: 96px;
|
height: 160px;
|
||||||
border-radius: 14px;
|
border-radius: 18px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.cover--empty {
|
.cover--empty {
|
||||||
|
|
@ -618,16 +619,16 @@ a.btn {
|
||||||
|
|
||||||
&::after {
|
&::after {
|
||||||
content: "♪";
|
content: "♪";
|
||||||
font-size: 1.4rem;
|
font-size: 1.8rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
&.cover--large::after {
|
&.cover--large::after {
|
||||||
font-size: 2.4rem;
|
font-size: 3.5rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------------------------------------------
|
/* ------------------------------------------------------------------------------------------------
|
||||||
* Bibliothèque : sections repliables et fenêtre de modification d'un morceau
|
* Bibliothèque : sections repliables et fenêtre de modification (morceau ou section)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
.library {
|
.library {
|
||||||
|
|
@ -648,9 +649,8 @@ a.btn {
|
||||||
|
|
||||||
.library-section__summary {
|
.library-section__summary {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: baseline;
|
align-items: center;
|
||||||
flex-wrap: wrap;
|
gap: 0.75rem;
|
||||||
gap: 0.25rem 0.75rem;
|
|
||||||
padding: 0.85rem 0;
|
padding: 0.85rem 0;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
list-style: none;
|
list-style: none;
|
||||||
|
|
@ -670,6 +670,72 @@ a.btn {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Nom et nombre de morceaux : restent à côté de l'image, quitte à passer sur deux lignes. */
|
||||||
|
.library-section__heading {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 0.25rem 0.75rem;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Étiquettes : sous un morceau, en barre de filtre au-dessus de la bibliothèque, ou en
|
||||||
|
suggestions dans la fenêtre de modification. Celle du filtre actif est pressée. */
|
||||||
|
.tag-list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.35rem;
|
||||||
|
|
||||||
|
&:not(:empty) {
|
||||||
|
margin-top: 0.4rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag-list--filter:not(:empty) {
|
||||||
|
margin-top: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.35rem;
|
||||||
|
padding: 0.2rem 0.7rem;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--accent) 15%, transparent);
|
||||||
|
color: var(--text);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
cursor: pointer;
|
||||||
|
|
||||||
|
&:hover {
|
||||||
|
background: color-mix(in srgb, var(--accent) 30%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
&[aria-pressed="true"] {
|
||||||
|
background: var(--accent-gradient);
|
||||||
|
color: var(--on-accent);
|
||||||
|
border-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
&:focus-visible {
|
||||||
|
outline: 2px solid #fff;
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.tag__count {
|
||||||
|
opacity: 0.7;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Image de la section, entre la flèche et le nom. */
|
||||||
|
.cover--section {
|
||||||
|
width: 96px;
|
||||||
|
height: 96px;
|
||||||
|
border-radius: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
.library-section__name {
|
.library-section__name {
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-size: 1.05rem;
|
font-size: 1.05rem;
|
||||||
|
|
@ -708,13 +774,13 @@ a.btn {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.track-editor {
|
.cover-editor {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
}
|
}
|
||||||
|
|
||||||
.track-editor__cover-fields {
|
.cover-editor__fields {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
@ -819,10 +885,21 @@ a.btn {
|
||||||
flex-basis: 100%;
|
flex-basis: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.track-editor {
|
.cover-editor {
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.cover {
|
||||||
|
width: 60px;
|
||||||
|
height: 60px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cover--large,
|
||||||
|
.cover--section {
|
||||||
|
width: 96px;
|
||||||
|
height: 96px;
|
||||||
|
}
|
||||||
|
|
||||||
.media-item__actions .btn,
|
.media-item__actions .btn,
|
||||||
.library-section__toolbar .btn {
|
.library-section__toolbar .btn {
|
||||||
width: auto;
|
width: auto;
|
||||||
|
|
|
||||||
42
src/features/tags.js
Normal file
42
src/features/tags.js
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
/**
|
||||||
|
* @file Étiquettes des morceaux de la bibliothèque : nettoyage de la liste envoyée par la page et
|
||||||
|
* comparaison sans tenir compte des majuscules.
|
||||||
|
*
|
||||||
|
* Utilisé par : web/routes/library.js (modification d'un morceau, ajout à la file par étiquette).
|
||||||
|
* Attention : la virgule sépare les étiquettes dans la page ; elle est donc retirée d'une étiquette.
|
||||||
|
* « Calme » et « calme » sont la même étiquette : la première écriture reçue est gardée.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const MAX_TAGS = 15;
|
||||||
|
const MAX_TAG_LENGTH = 30;
|
||||||
|
|
||||||
|
// Clé de comparaison d'une étiquette.
|
||||||
|
function tagKey(tag) {
|
||||||
|
return String(tag).toLocaleLowerCase("fr");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Liste d'étiquettes propre (sans doublon, ni vide, ni caractère de contrôle), ou null si
|
||||||
|
// `value` n'est pas un tableau.
|
||||||
|
function cleanTags(value) {
|
||||||
|
if (!Array.isArray(value)) return null;
|
||||||
|
const tags = new Map();
|
||||||
|
for (const raw of value) {
|
||||||
|
const tag = String(raw ?? "")
|
||||||
|
.replace(/[\u0000-\u001f,]/g, " ")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim()
|
||||||
|
.slice(0, MAX_TAG_LENGTH)
|
||||||
|
.trim();
|
||||||
|
if (tag && !tags.has(tagKey(tag))) {
|
||||||
|
tags.set(tagKey(tag), tag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...tags.values()].slice(0, MAX_TAGS);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasTag(entry, tag) {
|
||||||
|
const key = tagKey(tag);
|
||||||
|
return (entry.tags ?? []).some((item) => tagKey(item) === key);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { cleanTags, hasTag };
|
||||||
41
src/web/routes/coverUpload.js
Normal file
41
src/web/routes/coverUpload.js
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
/**
|
||||||
|
* @file Réception d'une image envoyée depuis la page (pochette d'un morceau, image d'une section) :
|
||||||
|
* middleware d'envoi et traitement commun aux deux routes.
|
||||||
|
*
|
||||||
|
* Utilisé par : web/routes/library.js et librarySections.js.
|
||||||
|
* Attention : le fichier reçu dans storage/temp est toujours supprimé, que l'image soit acceptée ou
|
||||||
|
* non ; seule sa conversion reste, dans storage/covers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import multer from "multer";
|
||||||
|
import { saveCoverFromImage } from "../storage/libraryCovers.js";
|
||||||
|
import { deleteCoverFile, discardUploadedFile, TEMP_DIR } from "../storage/storageManager.js";
|
||||||
|
|
||||||
|
const MAX_COVER_SIZE = 10 * 1024 * 1024;
|
||||||
|
|
||||||
|
// Champ « cover », une seule image.
|
||||||
|
const coverUpload = multer({
|
||||||
|
dest: TEMP_DIR,
|
||||||
|
limits: { fileSize: MAX_COVER_SIZE, files: 1, fields: 0 },
|
||||||
|
}).single("cover");
|
||||||
|
|
||||||
|
// Convertit l'image reçue, puis apply(nom) l'attache à son élément et renvoie la réponse JSON,
|
||||||
|
// ou null si l'élément n'existe plus (404, la nouvelle image est alors supprimée).
|
||||||
|
async function handleCoverUpload(req, res, apply) {
|
||||||
|
if (!req.file) {
|
||||||
|
return res.status(400).json({ error: "Aucune image reçue" });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const cover = await saveCoverFromImage(req.file.path);
|
||||||
|
const body = apply(cover);
|
||||||
|
if (!body) {
|
||||||
|
deleteCoverFile(cover);
|
||||||
|
return res.status(404).json({ error: "Élément introuvable" });
|
||||||
|
}
|
||||||
|
return res.json(body);
|
||||||
|
} finally {
|
||||||
|
discardUploadedFile(req.file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { coverUpload, handleCoverUpload };
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
/**
|
/**
|
||||||
* @file Routes /api/library : liste la bibliothèque et ses sections, modifie un morceau (titre,
|
* @file Routes /api/library : liste la bibliothèque et ses sections, modifie un morceau (titre,
|
||||||
* section, pochette), le supprime, et ajoute à la file un morceau, une section ou tout.
|
* section, étiquettes, pochette), le supprime, et ajoute à la file un morceau, ou tous ceux
|
||||||
|
* d'une section et/ou d'une étiquette.
|
||||||
*
|
*
|
||||||
* Utilisé par : web/server.js ; appelé par la page du jukebox.
|
* Utilisé par : web/server.js ; appelé par la page du jukebox.
|
||||||
* Attention : chaque changement émet « libraryUpdate » sur la file, que le flux /api/events relaie
|
* Attention : chaque changement émet « libraryUpdate » sur la file, que le flux /api/events relaie
|
||||||
|
|
@ -8,27 +9,21 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import multer from "multer";
|
import { setTrackCover } from "../storage/libraryCovers.js";
|
||||||
import { saveCoverFromImage, setTrackCover } from "../storage/libraryCovers.js";
|
|
||||||
import { findSection, getSections } from "../storage/librarySections.js";
|
import { findSection, getSections } from "../storage/librarySections.js";
|
||||||
import {
|
import {
|
||||||
createQueueTrackFromLibrary,
|
createQueueTrackFromLibrary,
|
||||||
deletePermanentTrack,
|
deletePermanentTrack,
|
||||||
discardUploadedFile,
|
|
||||||
findPermanentTrack,
|
findPermanentTrack,
|
||||||
getPermanentLibrary,
|
getPermanentLibrary,
|
||||||
TEMP_DIR,
|
|
||||||
updatePermanentTracks,
|
updatePermanentTracks,
|
||||||
} from "../storage/storageManager.js";
|
} from "../storage/storageManager.js";
|
||||||
import { serializeTrack, serializeTracks } from "../serializers.js";
|
import { serializeSections, serializeTrack, serializeTracks } from "../serializers.js";
|
||||||
|
import { cleanTags, hasTag } from "../../features/tags.js";
|
||||||
import { shuffle } from "../../features/utilities.js";
|
import { shuffle } from "../../features/utilities.js";
|
||||||
|
import { coverUpload, handleCoverUpload } from "./coverUpload.js";
|
||||||
import { librarySectionsRouter } from "./librarySections.js";
|
import { librarySectionsRouter } from "./librarySections.js";
|
||||||
|
|
||||||
const coverUpload = multer({
|
|
||||||
dest: TEMP_DIR,
|
|
||||||
limits: { fileSize: 10 * 1024 * 1024, files: 1, fields: 0 },
|
|
||||||
});
|
|
||||||
|
|
||||||
function cleanTitle(value) {
|
function cleanTitle(value) {
|
||||||
return String(value ?? "")
|
return String(value ?? "")
|
||||||
.replace(/[\u0000-\u001f]/g, "")
|
.replace(/[\u0000-\u001f]/g, "")
|
||||||
|
|
@ -41,7 +36,10 @@ function libraryRouter({ queue }) {
|
||||||
router.use("/sections", librarySectionsRouter({ queue }));
|
router.use("/sections", librarySectionsRouter({ queue }));
|
||||||
|
|
||||||
router.get("/", (req, res) => {
|
router.get("/", (req, res) => {
|
||||||
res.json({ tracks: serializeTracks(getPermanentLibrary()), sections: getSections() });
|
res.json({
|
||||||
|
tracks: serializeTracks(getPermanentLibrary()),
|
||||||
|
sections: serializeSections(getSections()),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.delete("/:libraryId", (req, res) => {
|
router.delete("/:libraryId", (req, res) => {
|
||||||
|
|
@ -56,7 +54,7 @@ function libraryRouter({ queue }) {
|
||||||
res.json({ removed: serializeTrack(track) });
|
res.json({ removed: serializeTrack(track) });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Corps : title et/ou sectionId (null : sans section).
|
// Corps : title, sectionId (null : sans section) et/ou tags (liste complète, [] pour aucune).
|
||||||
router.patch("/:libraryId", (req, res) => {
|
router.patch("/:libraryId", (req, res) => {
|
||||||
const fields = {};
|
const fields = {};
|
||||||
if (req.body?.title !== undefined) {
|
if (req.body?.title !== undefined) {
|
||||||
|
|
@ -72,6 +70,12 @@ function libraryRouter({ queue }) {
|
||||||
}
|
}
|
||||||
fields.sectionId = sectionId;
|
fields.sectionId = sectionId;
|
||||||
}
|
}
|
||||||
|
if (req.body?.tags !== undefined) {
|
||||||
|
fields.tags = cleanTags(req.body.tags);
|
||||||
|
if (!fields.tags) {
|
||||||
|
return res.status(400).json({ error: "Les étiquettes doivent être une liste" });
|
||||||
|
}
|
||||||
|
}
|
||||||
if (Object.keys(fields).length === 0) {
|
if (Object.keys(fields).length === 0) {
|
||||||
return res.status(400).json({ error: "Rien à modifier" });
|
return res.status(400).json({ error: "Rien à modifier" });
|
||||||
}
|
}
|
||||||
|
|
@ -89,25 +93,14 @@ function libraryRouter({ queue }) {
|
||||||
});
|
});
|
||||||
|
|
||||||
// Remplace la pochette par l'image envoyée (champ « cover »).
|
// Remplace la pochette par l'image envoyée (champ « cover »).
|
||||||
router.put("/:libraryId/cover", coverUpload.single("cover"), async (req, res) => {
|
router.put("/:libraryId/cover", coverUpload, (req, res) =>
|
||||||
if (!req.file) {
|
handleCoverUpload(req, res, (cover) => {
|
||||||
return res.status(400).json({ error: "Aucune image reçue" });
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (!findPermanentTrack(req.params.libraryId)) {
|
|
||||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
|
||||||
}
|
|
||||||
const cover = await saveCoverFromImage(req.file.path);
|
|
||||||
const track = setTrackCover(req.params.libraryId, cover);
|
const track = setTrackCover(req.params.libraryId, cover);
|
||||||
if (!track) {
|
if (!track) return null;
|
||||||
return res.status(404).json({ error: "Fichier permanent introuvable" });
|
|
||||||
}
|
|
||||||
queue.emit("libraryUpdate");
|
queue.emit("libraryUpdate");
|
||||||
res.json({ track: serializeTrack(track) });
|
return { track: serializeTrack(track) };
|
||||||
} finally {
|
})
|
||||||
discardUploadedFile(req.file);
|
);
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
router.delete("/:libraryId/cover", (req, res) => {
|
router.delete("/:libraryId/cover", (req, res) => {
|
||||||
const track = setTrackCover(req.params.libraryId, null);
|
const track = setTrackCover(req.params.libraryId, null);
|
||||||
|
|
@ -119,12 +112,15 @@ function libraryRouter({ queue }) {
|
||||||
});
|
});
|
||||||
|
|
||||||
// Ajoute la bibliothèque à la file, mélangée si shuffle vaut true. Avec sectionId, seulement
|
// Ajoute la bibliothèque à la file, mélangée si shuffle vaut true. Avec sectionId, seulement
|
||||||
// cette section (null : les morceaux sans section).
|
// cette section (null : les morceaux sans section) ; avec tag, seulement cette étiquette.
|
||||||
router.post("/enqueue-all", (req, res) => {
|
router.post("/enqueue-all", (req, res) => {
|
||||||
let entries = getPermanentLibrary();
|
let entries = getPermanentLibrary();
|
||||||
if (req.body?.sectionId !== undefined) {
|
if (req.body?.sectionId !== undefined) {
|
||||||
entries = entries.filter((entry) => (entry.sectionId ?? null) === req.body.sectionId);
|
entries = entries.filter((entry) => (entry.sectionId ?? null) === req.body.sectionId);
|
||||||
}
|
}
|
||||||
|
if (typeof req.body?.tag === "string" && req.body.tag) {
|
||||||
|
entries = entries.filter((entry) => hasTag(entry, req.body.tag));
|
||||||
|
}
|
||||||
if (req.body?.shuffle === true) {
|
if (req.body?.shuffle === true) {
|
||||||
shuffle(entries);
|
shuffle(entries);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,17 @@
|
||||||
/**
|
/**
|
||||||
* @file Routes /api/library/sections : crée, renomme, déplace et supprime les sections de la
|
* @file Routes /api/library/sections : crée, renomme, déplace et supprime les sections de la
|
||||||
* bibliothèque.
|
* bibliothèque, et change leur image.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { createSection, deleteSection, updateSection } from "../storage/librarySections.js";
|
import {
|
||||||
|
createSection,
|
||||||
|
deleteSection,
|
||||||
|
setSectionCover,
|
||||||
|
updateSection,
|
||||||
|
} from "../storage/librarySections.js";
|
||||||
|
import { serializeSection } from "../serializers.js";
|
||||||
|
import { coverUpload, handleCoverUpload } from "./coverUpload.js";
|
||||||
|
|
||||||
function librarySectionsRouter({ queue }) {
|
function librarySectionsRouter({ queue }) {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
@ -12,7 +19,7 @@ function librarySectionsRouter({ queue }) {
|
||||||
router.post("/", (req, res) => {
|
router.post("/", (req, res) => {
|
||||||
const section = createSection(req.body?.name);
|
const section = createSection(req.body?.name);
|
||||||
queue.emit("libraryUpdate");
|
queue.emit("libraryUpdate");
|
||||||
res.status(201).json({ section });
|
res.status(201).json({ section: serializeSection(section) });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Corps : name (nouveau nom) et/ou position (nouvel emplacement, 0 en tête).
|
// Corps : name (nouveau nom) et/ou position (nouvel emplacement, 0 en tête).
|
||||||
|
|
@ -26,7 +33,26 @@ function librarySectionsRouter({ queue }) {
|
||||||
return res.status(404).json({ error: "Section introuvable" });
|
return res.status(404).json({ error: "Section introuvable" });
|
||||||
}
|
}
|
||||||
queue.emit("libraryUpdate");
|
queue.emit("libraryUpdate");
|
||||||
res.json({ section });
|
res.json({ section: serializeSection(section) });
|
||||||
|
});
|
||||||
|
|
||||||
|
// Remplace l'image de la section par celle envoyée (champ « cover »).
|
||||||
|
router.put("/:sectionId/cover", coverUpload, (req, res) =>
|
||||||
|
handleCoverUpload(req, res, (cover) => {
|
||||||
|
const section = setSectionCover(req.params.sectionId, cover);
|
||||||
|
if (!section) return null;
|
||||||
|
queue.emit("libraryUpdate");
|
||||||
|
return { section: serializeSection(section) };
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
router.delete("/:sectionId/cover", (req, res) => {
|
||||||
|
const section = setSectionCover(req.params.sectionId, null);
|
||||||
|
if (!section) {
|
||||||
|
return res.status(404).json({ error: "Section introuvable" });
|
||||||
|
}
|
||||||
|
queue.emit("libraryUpdate");
|
||||||
|
res.json({ section: serializeSection(section) });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.delete("/:sectionId", (req, res) => {
|
router.delete("/:sectionId", (req, res) => {
|
||||||
|
|
@ -35,7 +61,7 @@ function librarySectionsRouter({ queue }) {
|
||||||
return res.status(404).json({ error: "Section introuvable" });
|
return res.status(404).json({ error: "Section introuvable" });
|
||||||
}
|
}
|
||||||
queue.emit("libraryUpdate");
|
queue.emit("libraryUpdate");
|
||||||
res.json({ removed: section });
|
res.json({ removed: serializeSection(section) });
|
||||||
});
|
});
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
|
|
|
||||||
|
|
@ -1,25 +1,36 @@
|
||||||
/**
|
/**
|
||||||
* @file Prépare les morceaux pour l'API : retire le chemin et le nom du fichier sur le disque, et
|
* @file Prépare les morceaux et les sections de la bibliothèque pour l'API : retire le chemin et le
|
||||||
* remplace le nom de la pochette par son adresse.
|
* nom du fichier sur le disque, et remplace le nom de la pochette ou de l'image par son adresse.
|
||||||
*
|
*
|
||||||
* Utilisé par : music/queue.js (snapshot) et les routes web.
|
* Utilisé par : music/queue.js (snapshot) et les routes web.
|
||||||
* Attention : tout morceau envoyé à une page ou à un client passe par ici.
|
* Attention : tout morceau envoyé à une page ou à un client passe par ici.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// Remplace le nom de fichier `cover` (storage/covers) par l'adresse coverUrl, servie par
|
||||||
|
// web/server.js.
|
||||||
|
function withCoverUrl({ cover, ...item }) {
|
||||||
|
return cover ? { ...item, coverUrl: `/covers/${encodeURIComponent(cover)}` } : item;
|
||||||
|
}
|
||||||
|
|
||||||
function serializeTrack(track) {
|
function serializeTrack(track) {
|
||||||
if (!track) {
|
if (!track) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { path: _path, storedName: _storedName, cover, ...publicTrack } = track;
|
const { path: _path, storedName: _storedName, ...publicTrack } = track;
|
||||||
if (cover) {
|
return withCoverUrl(publicTrack);
|
||||||
publicTrack.coverUrl = `/covers/${encodeURIComponent(cover)}`;
|
|
||||||
}
|
|
||||||
return publicTrack;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function serializeTracks(tracks = []) {
|
function serializeTracks(tracks = []) {
|
||||||
return tracks.map(serializeTrack);
|
return tracks.map(serializeTrack);
|
||||||
}
|
}
|
||||||
|
|
||||||
export { serializeTrack, serializeTracks };
|
function serializeSection(section) {
|
||||||
|
return section ? withCoverUrl(section) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function serializeSections(sections = []) {
|
||||||
|
return sections.map(serializeSection);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { serializeSection, serializeSections, serializeTrack, serializeTracks };
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,10 @@
|
||||||
/**
|
/**
|
||||||
* @file Pochettes des morceaux de la bibliothèque : reprise de la pochette intégrée au fichier audio,
|
* @file Pochettes des morceaux de la bibliothèque : reprise de la pochette intégrée au fichier audio,
|
||||||
* remplacement par une image envoyée depuis la page, retrait.
|
* remplacement par une image envoyée depuis la page, retrait. Convertit aussi les images des
|
||||||
|
* sections (saveCoverFromImage).
|
||||||
*
|
*
|
||||||
* Utilisé par : music/ingest.js (nouveau morceau), storage/libraryMetadata.js (morceaux plus
|
* Utilisé par : music/ingest.js (nouveau morceau), storage/libraryMetadata.js (morceaux plus
|
||||||
* anciens), web/routes/library.js (envoi et retrait depuis la page).
|
* anciens), web/routes/library.js (retrait depuis la page), web/routes/coverUpload.js (envoi).
|
||||||
* Attention :
|
* Attention :
|
||||||
* - Le champ `cover` d'une entrée vaut le nom du fichier dans storage/covers, null si le morceau
|
* - Le champ `cover` d'une entrée vaut le nom du fichier dans storage/covers, null si le morceau
|
||||||
* n'a pas de pochette, et il est absent tant que la pochette intégrée n'a pas été cherchée.
|
* n'a pas de pochette, et il est absent tant que la pochette intégrée n'a pas été cherchée.
|
||||||
|
|
@ -11,6 +12,7 @@
|
||||||
* peut garder une pochette en cache indéfiniment (servie sous /covers par web/server.js).
|
* peut garder une pochette en cache indéfiniment (servie sous /covers par web/server.js).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { createCoverImage, detectImageFormat } from "../../media/coverArt.js";
|
import { createCoverImage, detectImageFormat } from "../../media/coverArt.js";
|
||||||
|
|
@ -29,6 +31,8 @@ function httpError(status, message, cause) {
|
||||||
async function writeCover(inputPath, { create = createCoverImage, inputFormat } = {}) {
|
async function writeCover(inputPath, { create = createCoverImage, inputFormat } = {}) {
|
||||||
const name = `${randomUUID()}.jpg`;
|
const name = `${randomUUID()}.jpg`;
|
||||||
try {
|
try {
|
||||||
|
// Le dossier est créé au démarrage du serveur, mais peut avoir été supprimé depuis.
|
||||||
|
fs.mkdirSync(COVERS_DIR, { recursive: true });
|
||||||
await create(inputPath, path.join(COVERS_DIR, name), { inputFormat });
|
await create(inputPath, path.join(COVERS_DIR, name), { inputFormat });
|
||||||
return name;
|
return name;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -1,17 +1,24 @@
|
||||||
/**
|
/**
|
||||||
* @file Sections de la bibliothèque : liste ordonnée de groupes nommés, enregistrée dans
|
* @file Sections de la bibliothèque : liste ordonnée de groupes nommés, avec une image facultative,
|
||||||
* storage/runtime/sections.json. Chaque morceau désigne la sienne par son champ `sectionId`.
|
* enregistrée dans storage/runtime/sections.json. Chaque morceau désigne la sienne par son
|
||||||
|
* champ `sectionId`.
|
||||||
*
|
*
|
||||||
* Utilisé par : web/routes/librarySections.js, web/routes/library.js et uploads.js (section
|
* Utilisé par : web/routes/librarySections.js, web/routes/library.js et uploads.js (section
|
||||||
* choisie pour un morceau).
|
* choisie pour un morceau).
|
||||||
* Attention : supprimer une section remet ses morceaux « sans section », sans les supprimer. Un
|
* Attention : supprimer une section remet ses morceaux « sans section », sans les supprimer, et
|
||||||
* fichier absent vaut une liste vide.
|
* supprime son image. Un fichier absent vaut une liste vide. L'image (`cover`) est un nom de
|
||||||
|
* fichier de storage/covers, créé comme les pochettes des morceaux (libraryCovers.js).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { getPermanentLibrary, RUNTIME_DIR, updatePermanentTracks } from "./storageManager.js";
|
import {
|
||||||
|
deleteCoverFile,
|
||||||
|
getPermanentLibrary,
|
||||||
|
RUNTIME_DIR,
|
||||||
|
updatePermanentTracks,
|
||||||
|
} from "./storageManager.js";
|
||||||
|
|
||||||
const SECTIONS_FILE = path.join(RUNTIME_DIR, "sections.json");
|
const SECTIONS_FILE = path.join(RUNTIME_DIR, "sections.json");
|
||||||
const MAX_SECTIONS = 100;
|
const MAX_SECTIONS = 100;
|
||||||
|
|
@ -99,9 +106,35 @@ function deleteSection(id) {
|
||||||
|
|
||||||
const [removed] = sections.splice(index, 1);
|
const [removed] = sections.splice(index, 1);
|
||||||
writeSections(sections);
|
writeSections(sections);
|
||||||
|
deleteCoverFile(removed.cover);
|
||||||
const orphans = getPermanentLibrary().filter((entry) => entry.sectionId === id);
|
const orphans = getPermanentLibrary().filter((entry) => entry.sectionId === id);
|
||||||
updatePermanentTracks(new Map(orphans.map((entry) => [entry.id, { sectionId: null }])));
|
updatePermanentTracks(new Map(orphans.map((entry) => [entry.id, { sectionId: null }])));
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { createSection, deleteSection, findSection, getSections, updateSection };
|
// Donne l'image `name` (null : aucune) à la section et supprime l'ancienne. Renvoie la section,
|
||||||
|
// ou null si elle n'existe plus : la nouvelle image est alors supprimée.
|
||||||
|
function setSectionCover(id, name) {
|
||||||
|
const sections = getSections();
|
||||||
|
const section = sections.find((item) => item.id === id);
|
||||||
|
if (!section) {
|
||||||
|
deleteCoverFile(name);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const previous = section.cover;
|
||||||
|
section.cover = name;
|
||||||
|
writeSections(sections);
|
||||||
|
if (previous && previous !== name) {
|
||||||
|
deleteCoverFile(previous);
|
||||||
|
}
|
||||||
|
return section;
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
createSection,
|
||||||
|
deleteSection,
|
||||||
|
findSection,
|
||||||
|
getSections,
|
||||||
|
setSectionCover,
|
||||||
|
updateSection,
|
||||||
|
};
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
/**
|
/**
|
||||||
* @file Vérifie les sections de la bibliothèque : création, renommage, déplacement, et suppression qui
|
* @file Vérifie les sections de la bibliothèque : création, renommage, déplacement, image, et
|
||||||
* remet ses morceaux sans section.
|
* suppression qui remet ses morceaux sans section.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import test from "node:test";
|
import test from "node:test";
|
||||||
|
|
@ -15,6 +15,7 @@ const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "palico-section
|
||||||
process.chdir(temporaryDirectory);
|
process.chdir(temporaryDirectory);
|
||||||
const storage = await import("../src/web/storage/storageManager.js");
|
const storage = await import("../src/web/storage/storageManager.js");
|
||||||
const sections = await import("../src/web/storage/librarySections.js");
|
const sections = await import("../src/web/storage/librarySections.js");
|
||||||
|
const { serializeSection } = await import("../src/web/serializers.js");
|
||||||
storage.ensureStorageLayout();
|
storage.ensureStorageLayout();
|
||||||
test.after(() => {
|
test.after(() => {
|
||||||
process.chdir(originalDirectory);
|
process.chdir(originalDirectory);
|
||||||
|
|
@ -66,3 +67,25 @@ test("deleting a section keeps its tracks, without a section", () => {
|
||||||
assert.equal(storage.findPermanentTrack(inKept).sectionId, kept.id);
|
assert.equal(storage.findPermanentTrack(inKept).sectionId, kept.id);
|
||||||
assert.equal(sections.deleteSection(doomed.id), null);
|
assert.equal(sections.deleteSection(doomed.id), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a section image is replaced, removed, and deleted with its section", () => {
|
||||||
|
const section = sections.createSection("Avec image");
|
||||||
|
const coverFile = (name) => path.join(storage.COVERS_DIR, name);
|
||||||
|
fs.writeFileSync(coverFile("first.jpg"), "jpeg");
|
||||||
|
fs.writeFileSync(coverFile("second.jpg"), "jpeg");
|
||||||
|
|
||||||
|
sections.setSectionCover(section.id, "first.jpg");
|
||||||
|
assert.equal(serializeSection(sections.findSection(section.id)).coverUrl, "/covers/first.jpg");
|
||||||
|
assert.equal("cover" in serializeSection(sections.findSection(section.id)), false);
|
||||||
|
|
||||||
|
sections.setSectionCover(section.id, "second.jpg");
|
||||||
|
assert.equal(fs.existsSync(coverFile("first.jpg")), false);
|
||||||
|
|
||||||
|
// Section disparue : la nouvelle image est supprimée au lieu de rester orpheline.
|
||||||
|
fs.writeFileSync(coverFile("orphan.jpg"), "jpeg");
|
||||||
|
assert.equal(sections.setSectionCover("unknown", "orphan.jpg"), null);
|
||||||
|
assert.equal(fs.existsSync(coverFile("orphan.jpg")), false);
|
||||||
|
|
||||||
|
sections.deleteSection(section.id);
|
||||||
|
assert.equal(fs.existsSync(coverFile("second.jpg")), false);
|
||||||
|
});
|
||||||
|
|
|
||||||
29
test/tags.test.js
Normal file
29
test/tags.test.js
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
/**
|
||||||
|
* @file Vérifie le nettoyage des étiquettes (espaces, virgules, doublons, limites) et leur comparaison
|
||||||
|
* sans tenir compte des majuscules.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { cleanTags, hasTag } from "../src/features/tags.js";
|
||||||
|
|
||||||
|
test("tags are trimmed, deduplicated and kept in their first spelling", () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
cleanTags([" Épique ", "calme", "épique", "", "a,b", "Monster\u0007 Hunter", null]),
|
||||||
|
["Épique", "calme", "a b", "Monster Hunter"]
|
||||||
|
);
|
||||||
|
assert.deepEqual(cleanTags([]), []);
|
||||||
|
assert.equal(cleanTags("épique, calme"), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tags are limited in number and length", () => {
|
||||||
|
const many = Array.from({ length: 20 }, (_, index) => `tag${index}`);
|
||||||
|
assert.equal(cleanTags(many).length, 15);
|
||||||
|
assert.equal(cleanTags(["x".repeat(50)])[0].length, 30);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("tag matching ignores case", () => {
|
||||||
|
assert.equal(hasTag({ tags: ["Épique"] }, "épique"), true);
|
||||||
|
assert.equal(hasTag({ tags: ["calme"] }, "épique"), false);
|
||||||
|
assert.equal(hasTag({}, "épique"), false);
|
||||||
|
});
|
||||||
Loading…
Add table
Add a link
Reference in a new issue