var picts = null; var api_url = "/api/images"; var img_url = "/images/"; function get_picts(then, then_value) { fetch(api_url) .then(function(response) { return response.json(); }) .then(function(my_picts) { picts = my_picts; if (then) then(then_value); }) .catch(function(error) { display_error(error); }); } function show_mozaic() { if (!picts) { get_picts(show_mozaic); return; } while (document.body.hasChildNodes()) document.body.removeChild(document.body.lastChild); picts.forEach(function (pict) { var figure = document.createElement("figure"); figure.className = "moz"; var img = document.createElement("img"); img.src = img_url + pict.name; img.alt = pict.name; var link = document.createElement("a"); link.onclick = function(e) { window.history.pushState(null, "YouP0m", link.href); sync(); return false; }; link.href = "/" + pict.name; link.appendChild(img); figure.appendChild(link); document.body.appendChild(figure); }); } function show_picture(id) { if (!picts) { get_picts(show_picture, id); return; } if (id == null || id == "") id = picts[Math.floor(Math.random() * picts.length)].name; var i = parseInt(id); if (!isNaN(i) && i < picts.length) { display_picture(picts[i], (picts.length+i-1)%picts.length); } else { var found = false; picts.forEach(function (pict, index) { if (pict.name == id) { found = true; display_picture(pict, picts[(picts.length+index-1)%picts.length].name); } }); if (!found) { get_picture(id); } } } function get_picture(id) { if (id == null) id = "last"; fetch(api_url + "/" + id) .then(function(response) { return response.json(); }) .then(function(my_pict) { display_picture(my_pict); }) .catch(function(error) { display_error(error); }); } function display_picture(pict, next) { while (document.body.hasChildNodes()) document.body.removeChild(document.body.lastChild); var figure = document.createElement("figure"); figure.className = "big"; var img = document.createElement("img"); img.src = img_url + pict.name; img.alt = pict.name; if (next != null) { var link = document.createElement("a"); link.onclick = function(e) { window.history.pushState(null, "YouP0m", link.href); sync(); return false; }; link.href = "/" + next; link.appendChild(img); figure.appendChild(link); } else { figure.appendChild(img); } document.body.appendChild(figure); } function display_error(msg) { $$("body")[0].innerHTML = '

An error occurs

' + msg + '

'; } function sync() { path = window.location.pathname.slice(1); if (path == "all") show_mozaic(); else show_picture(path); } window.onpopstate = sync; document.onreadystatechange = function() { if (document.readyState == "complete") sync(); }