webmusic.js: navigate through files more smartly

This commit is contained in:
Leah 2021-03-06 22:52:55 +01:00 committed by Leah (ctucx)
parent 822996211f
commit 9f90eed214

View file

@ -1,7 +1,6 @@
let gstate = "idle"; let gstate = "idle";
let repeat = false; let repeat = false;
let continuelist = true; let continuelist = true;
let queue = [];
let total = 0; let total = 0;
let index = 0; let index = 0;
@ -25,7 +24,7 @@ window.onkeyup = function (event) {
case " ": case " ":
case "p": case "p":
if (gstate == "idle" && total !== 0) { if (gstate == "idle" && total !== 0) {
playSong(queue[0]) playSong(index)
} else { } else {
togglePlayback(); togglePlayback();
} }
@ -65,6 +64,28 @@ window.onkeyup = function (event) {
} }
}; };
function initState() {
const dirElements = document.querySelectorAll(".dir");
const fileElements = document.querySelectorAll(".file");
let id = 0;
dirElements.forEach(function(element){
element.id = id++;
});
fileElements.forEach(function(element){
element.id = id++;
element.addEventListener("click", function(event) {
event.preventDefault();
event.stopPropagation();
playSong(event.target.id);
});
});
total = id;
}
function togglePlayback() { function togglePlayback() {
if (sound.playing()) { if (sound.playing()) {
@ -82,19 +103,25 @@ function setState(state) {
} }
function playSong(url) { function playSong(id) {
let element = document.getElementById(id);
if (element === null) return;
if (element.classList.contains('dir')) return;
if (document.getElementsByClassName("playing").length > 0) { if (document.getElementsByClassName("playing").length > 0) {
document.getElementsByClassName("playing")[0].classList.remove("playing"); document.getElementsByClassName("playing")[0].classList.remove("playing");
} }
index = queue.indexOf(url); index = element.id;
sound.stop(); sound.stop();
sound.unload(); sound.unload();
sound = null; sound = null;
delete sound; delete sound;
sound = new Howl({ sound = new Howl({
src: [url], src: [element.href],
html5: true html5: true
}); });
@ -102,7 +129,7 @@ function playSong(url) {
sound.play(); sound.play();
sound.loop(repeat); sound.loop(repeat);
document.querySelectorAll('[onclick="playSong(\''+url+'\')"]')[0].classList.add("playing"); element.classList.add("playing");
sound.on("play", function () { sound.on("play", function () {
setState("playing"); setState("playing");
@ -157,15 +184,11 @@ function updateState() {
document.getElementById("flags").innerHTML = flags + "]"; document.getElementById("flags").innerHTML = flags + "]";
} }
function initState() {
total = queue.length;
}
function previousTrack() { function previousTrack() {
if (index-- === 0) index = total-1; if (index-- === 0) index = total-1;
if (continuelist) { if (continuelist) {
playSong(queue[index]) playSong(index)
} }
} }
@ -173,7 +196,7 @@ function nextTrack() {
if (++index === total) index = 0; if (++index === total) index = 0;
if (continuelist) { if (continuelist) {
playSong(queue[index]) playSong(index)
} }
} }