collage-maker/web/choose.js

130 lines
3.2 KiB
JavaScript

"use strict";
// elements
/** @type {HTMLButtonElement} */
let loadAlbumsBtn
/** @type {HTMLButtonElement} */
let loadPhotosBtn
/** @type {HTMLSelectElement} */
let albumSelect
/** @type {HTMLParagraphElement} */
let noticeP
/** @type {HTMLDialogElement} */
let noticeDialog
/** @type {HTMLDivElement} */
let albumPhotosDiv
/** @type {HTMLDivElement} */
let selectedPhotosDiv
/** @type {HTMLImageElement} */
let selectedPhotoImg
function main() {
albumSelect = document.getElementById("album_selector")
loadAlbumsBtn = document.getElementById("load_albums_button")
loadPhotosBtn = document.getElementById("load_photos_button")
noticeDialog = document.getElementById("notice_dialog")
albumPhotosDiv = document.getElementById("album_photos")
selectedPhotosDiv = document.getElementById("selected_photos")
noticeP = document.getElementById("notice_p")
loadAlbumsBtn.onclick = () => loadAlbums()
loadPhotosBtn.onclick = () => loadPhotos()
/**
* @type HTMLImageElement[]
*/
const selectedPhotos = selectedPhotosDiv.getElementsByTagName("img")
for (const img of selectedPhotos) {
img.onclick = () => {
selectedPhotoImg?.classList.remove("current")
selectedPhotoImg = img
selectedPhotoImg.classList.add("current")
}
}
selectedPhotos[0].click()
}
function loadAlbums() {
(async () => {
try {
closeNotice()
const resp = await fetch("get-albums")
const albums = await resp.json()
if(albums.length == 0) {
showNotice("No Albums found")
return
}
albumSelect.replaceChildren() // This empties existing options
for(const album of albums) {
albumSelect.add(new Option(album.Title, album.UID))
}
} catch(e) {
console.log(e)
}
})();
}
function closeNotice() {
noticeDialog.close()
}
/**
* @param {string} notice
*/
function showNotice(notice) {
noticeP.textContent = notice
noticeDialog.show()
}
function loadPhotos() {
closeNotice()
const selected = albumSelect.selectedOptions
if(selected.length != 1) {
showNotice("Select an album to load photos")
return
}
const [elem] = selected;
(async () => {
try {
const resp = await fetch(`load-photos/${elem.value}`)
/**
* @type String[]
*/
const photos = await resp.json()
if(photos.length == 0) {
showNotice("No Photos found")
return
}
albumPhotosDiv.replaceChildren()
for(const url of photos) {
const img = new Image()
img.src = url
albumPhotosDiv.appendChild(img)
}
/**
* @type HTMLImageElement[]
*/
const photoImgs = albumPhotosDiv.children
for(const photo of photoImgs) {
photo.onclick = () => {
selectedPhotoImg.src = photo.src
}
}
} catch(e) {
console.log(e)
}
})();
}
main()