aboutsummaryrefslogtreecommitdiff
path: root/assets_src/js/like.js
blob: feae345c9f3e5c795444e1c334b1abda7767ff9d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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 ' : ''}geil finden`;
					});
					el.addEventListener('mouseout', () => cap.textContent = 'Finden das geil');
				}
			} else {
				el.classList.add('disabled');
			}

		});
});