aboutsummaryrefslogtreecommitdiff
path: root/assets_src/js/list.js
blob: 0d865c7673e5ca41f01fe67c6d1ce402f399ea7b (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
92
93
94
95
96
97
98
99
100
import 'babel-polyfill';
import * as search from './lib/search';
import * as dom from './lib/dom';
import * as ajax from './lib/ajax';

async function resultClicked(grilId) {
	let response = null;
	try {
		response = await ajax.post(
			window.location,
			'id=' + grilId, {
				headers: {
					'Content-type': 'application/x-www-form-urlencoded'
				}
			});
	} catch (e) {
		alert(e.message);
		return;
	}
	document.getElementById('gril-list').innerHTML += response;
}

async function updateGrilOrder(gril, pos) {
	return await ajax.post(
		`${window.location}/order`,
		`gril=${gril}&pos=${pos}`, {
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
			}
		});
}

function getCurrentOrder(gril) {
	const els = document.querySelectorAll('#gril-list > li')

	for (let i = 0; i < els.length; i++) {
		if (els[i].id === gril) {
			console.log(i);
			return i;
		}
	}
	return -1;
}

async function listButtonHandler(e) {
	let liFilter = x => x.tagName && x.tagName.toLowerCase() === 'li';
	let cItem = dom.closest(e.target, liFilter);
	let pItem = dom.previous(cItem, liFilter),
	    nItem = dom.next(dom.next(cItem, liFilter), liFilter);
	switch (e.target.classList[0]) {
	case 'gril-sort-up':
		try {
			await updateGrilOrder(cItem.id, getCurrentOrder(cItem.id) - 1);
		} catch(e) {
		 	alert(e.message);
		}
		cItem.parentNode.insertBefore(cItem, pItem);
		break;
	case 'gril-sort-down':
		try {
			await updateGrilOrder(cItem.id, getCurrentOrder(cItem.id) + 1);
		} catch(e) {
			alert(e.message);
		}

		if (nItem) {
			cItem.parentNode.insertBefore(cItem, nItem);
		} else {
			cItem.parentNode.appendChild(cItem);
		}
		break;
	case 'gril-delete':
		try {
			await ajax.del(
				`${window.location}/order`,
				`gril=${cItem.id}`, {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded',
					}
				});
			cItem.parentNode.removeChild(cItem);
		} catch(e) {
			alert(e.message);
		}
		break;
	}
}

function main() {
	let is = new search.InstantSearch(
		document.getElementById('gril-add-search'),
		document.getElementById('search-results'));
	is.resultClicked = resultClicked;
	document.getElementById('gril-list').addEventListener(
		'click',
		listButtonHandler,
		true);
}

dom.ready(main);