Files
bibliogame/public/assets/js/app.js
T
2026-09-29 10:45:14 +02:00

109 lines
3.4 KiB
JavaScript

document.addEventListener("DOMContentLoaded", () =>
{
const boutonRecherche = document.getElementById("btnRechercheApi");
const champRecherche = document.getElementById("rechercheApi");
const zoneResultats = document.getElementById("resultatsApi");
const formAppliquer = document.getElementById("formAppliquerApi");
const champRawgId = document.getElementById("rawgId");
if (!boutonRecherche || !champRecherche || !zoneResultats)
{
return;
}
const lancerRecherche = async () =>
{
const terme = champRecherche.value.trim();
if (terme === "")
{
zoneResultats.hidden = true;
zoneResultats.innerHTML = "";
return;
}
boutonRecherche.disabled = true;
boutonRecherche.textContent = "Recherche…";
try
{
const reponse = await fetch("/jeux/api/rechercher?q=" + encodeURIComponent(terme));
const donnees = await reponse.json();
afficherResultats(donnees.resultats || []);
}
catch (erreur)
{
zoneResultats.hidden = false;
zoneResultats.innerHTML = "<p class=\"text-muted\">Impossible de contacter l'API pour le moment.</p>";
}
finally
{
boutonRecherche.disabled = false;
boutonRecherche.textContent = "Rechercher";
}
};
const afficherResultats = (resultats) =>
{
zoneResultats.hidden = false;
if (resultats.length === 0)
{
zoneResultats.innerHTML = "<p class=\"text-muted\">Aucun résultat trouvé.</p>";
return;
}
zoneResultats.innerHTML = "";
resultats.forEach((jeu) =>
{
const carte = document.createElement("article");
carte.className = "api-result";
const image = document.createElement("img");
image.src = jeu.jaquetteUrl || "/assets/img/jaquette-manquante.svg";
image.alt = "Jaquette de " + (jeu.titre || "jeu");
const infos = document.createElement("div");
const titre = document.createElement("h3");
titre.textContent = jeu.titre || "Sans titre";
const meta = document.createElement("p");
const genres = (jeu.genres || []).join(", ");
meta.textContent = [jeu.dateSortie || "Date inconnue", genres].filter(Boolean).join(" · ");
infos.appendChild(titre);
infos.appendChild(meta);
const bouton = document.createElement("button");
bouton.type = "button";
bouton.className = "btn btn-sm btn-neon";
bouton.textContent = "Utiliser";
bouton.addEventListener("click", () =>
{
if (!formAppliquer || !champRawgId)
{
return;
}
champRawgId.value = String(jeu.rawgId);
formAppliquer.submit();
});
carte.appendChild(image);
carte.appendChild(infos);
carte.appendChild(bouton);
zoneResultats.appendChild(carte);
});
};
boutonRecherche.addEventListener("click", lancerRecherche);
champRecherche.addEventListener("keydown", (event) =>
{
if (event.key === "Enter")
{
event.preventDefault();
lancerRecherche();
}
});
});