www/js/main.js

129 lines
2.9 KiB
JavaScript

const button = document.getElementsByTagName('button')[0]
const menu = document.getElementById('menu')
function toggleMenu() {
if (menu.className == '') {
menu.className = button.className = 'active'
menu.style.maxHeight = menu.scrollHeight + 'px'
}
else {
menu.className = button.className = ''
menu.style.maxHeight = null
}
}
button.onclick = toggleMenu
if (getUser())
for (el of document.getElementsByClassName('logged'))
el.style.display = ''
else
for (el of document.getElementsByClassName('non-logged'))
el.style.display = ''
async function checkStatus(url, data = {}) {
try {
const response = await fetch(url, data)
return response.ok
} catch (err) {
return false
}
}
async function fetchJSON(url) {
try {
const response = await fetch(url)
if (!response.ok)
return false
const json = await response.json()
return json
}
catch (error) {
return false
}
}
async function checkLogin(login) {
return await checkStatus(`/api/checklogin/${login}`)
}
async function checkPassword(login, password) {
return await checkStatus('/api/checkpassword', {
method: 'POST',
body: `login=${login}&password=${password}`
})
}
function getUser() {
let user = {}
if (sessionStorage.login && sessionStorage.password) {
user.login = sessionStorage.login
user.password = sessionStorage.password
}
else if (localStorage.login && localStorage.password) {
user.login = localStorage.login
user.password = localStorage.password
}
else
return false
return user
}
const cachePeople = {}
const cacheVerse = {}
const grid = document.getElementById('grid')
async function verseToGrid(i) {
const div = document.createElement('div')
div.className = 'verse'
div.style.display = 'none'
grid.appendChild(div)
const verse = cacheVerse[i]
const id = verse.AUTHOR
if (!cachePeople[id]) {
cachePeople[id] = await fetchJSON(`/api/people/${id}`)
}
const author = cachePeople[id]
if (!verse.PRE) {
const r = await fetch(`/api/pre/${i}`)
verse.PRE = await r.text()
}
div.onclick = () => window.open(`/${i}`, '_self')
div.classList.add(verse.GENRE)
div.innerHTML = `<h2>${verse.TITLE}</h2><a href="/${author.LOGIN}">${author.NAME} ${author.SUBNAME}</a><pre>${verse.PRE}</pre>`
div.style.display = 'block'
return div
}
let Part = 0
function addVersePart() {
fetchJSON(`/api/versepart/${Part++}`)
.then(result => {
if (result) {
const arr = Object.keys(result)
const first = arr[0]
arr.reverse()
arr.forEach(async i => {
cacheVerse[i] = result[i]
const div = await verseToGrid(i)
if (i == first) {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
addVersePart()
console.log(2)
observer.unobserve(entry.target)
}
})
})
observer.observe(div)
}
})
}
})
}
window.onload = addVersePart