commit deb0a1e49f3319bd672851100b7ffee9b0871e0c
parent 863b2b2817e180c3db9f64e59db3201dcfd527e1
Author: ctucx <c@ctu.cx>
Date: Sat, 6 Mar 2021 22:52:55 +0100
parent 863b2b2817e180c3db9f64e59db3201dcfd527e1
Author: ctucx <c@ctu.cx>
Date: Sat, 6 Mar 2021 22:52:55 +0100
webmusic.js: navigate through files more smartly
1 file changed, 35 insertions(+), 12 deletions(-)
diff --git a/webmusic.js b/webmusic.js @@ -1,7 +1,6 @@ let gstate = "idle"; let repeat = false; let continuelist = true; -let queue = []; let total = 0; let index = 0; @@ -25,7 +24,7 @@ window.onkeyup = function (event) { case " ": case "p": if (gstate == "idle" && total !== 0) { - playSong(queue[0]) + playSong(index) } else { 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() { 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) { document.getElementsByClassName("playing")[0].classList.remove("playing"); } - index = queue.indexOf(url); + index = element.id; + sound.stop(); sound.unload(); sound = null; delete sound; sound = new Howl({ - src: [url], + src: [element.href], html5: true }); @@ -102,7 +129,7 @@ function playSong(url) { sound.play(); sound.loop(repeat); - document.querySelectorAll('[onclick="playSong(\''+url+'\')"]')[0].classList.add("playing"); + element.classList.add("playing"); sound.on("play", function () { setState("playing"); @@ -157,15 +184,11 @@ function updateState() { document.getElementById("flags").innerHTML = flags + "]"; } -function initState() { - total = queue.length; -} - function previousTrack() { if (index-- === 0) index = total-1; if (continuelist) { - playSong(queue[index]) + playSong(index) } } @@ -173,7 +196,7 @@ function nextTrack() { if (++index === total) index = 0; if (continuelist) { - playSong(queue[index]) + playSong(index) } }