import * as ajax from './lib/ajax'; import * as dom from './lib/dom'; async function updateLikeCount(el) { const type = parseInt(el.getAttribute('content-type'), 10); const contentId = parseInt(el.getAttribute('content-id'), 10); if (isNaN(type) || isNaN(contentId)) { return; } const count = await ajax.get(`/api/likes/count?id=${contentId}&type=${type}`, {}); dom.firstChild(el, e => e.classList.contains('like-count')).textContent = count; } async function isLikedByCurrentUser(el) { const type = parseInt(el.getAttribute('content-type'), 10); const contentId = parseInt(el.getAttribute('content-id'), 10); const userId = parseInt(el.getAttribute('update-with'), 10); if (isNaN(type) || isNaN(contentId) || isNaN(userId)) { return; } const b = await ajax.get(`/api/likes/liked_by?id=${contentId}&type=${type}&user=${userId}`, {}); console.log(b); return b === 'true'; } async function updateLikeByCurrentUser(el, to) { const type = parseInt(el.getAttribute('content-type'), 10); const contentId = parseInt(el.getAttribute('content-id'), 10); const userId = parseInt(el.getAttribute('update-with'), 10); if (isNaN(type) || isNaN(contentId) || isNaN(userId)) { return; } updateLikeClass(el, to); if (to) { await ajax.put('/api/likes', `id=${contentId}&type=${type}&user=${userId}`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }); } else { await ajax.del('/api/likes', `id=${contentId}&type=${type}&user=${userId}`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }); } const cont = dom.firstChild(el, e => e.classList.contains('like-count')); cont.textContent = parseInt(cont.textContent, 10) + (to ? 1 : -1); } function updateLikeClass(el, to) { el.classList.toggle('liked', to); } dom.ready(() => { dom.withClass('like-div') .forEach(async el => { updateLikeCount(el); const userId = parseInt(el.getAttribute('update-with'), 10); let liked = await isLikedByCurrentUser(el); updateLikeClass(el, liked); if (!isNaN(userId)) { el.addEventListener('click', async () => { liked = !liked; await updateLikeByCurrentUser(el, liked); }); const cap = dom.firstChild(el, e => e.classList.contains('like-caption')); if (cap) { el.addEventListener('mouseover', () => { cap.textContent = liked ? 'nicht mehr approven' : 'approven!'; }); el.addEventListener('mouseout', () => cap.textContent = 'approven'); } } else { el.classList.add('disabled'); } }); });