aboutsummaryrefslogtreecommitdiff
path: root/assets_src/js/list.js
blob: b3541e05bc227df084068ffc8256336eb795e604 (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
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',
        } });
}

async function listButtonHandler(e) {
	let liFilter = x => x.tagName && x.tagName.toLowerCase() === 'li';
	let item = dom.closest(e.target, liFilter);
	let pItem = dom.previous(item, liFilter),
	    nItem = dom.next(dom.next(item, liFilter), liFilter);
	switch (e.target.classList[0]) {
	case 'gril-sort-up':
        try {
            await updateGrilOrder(item.id, -1);
        } catch(e) {
            alert(e.message);
        }
		item.parentNode.insertBefore(item, pItem);
		break;
	case 'gril-sort-down':
        try {
            await updateGrilOrder(item.id, 1);
        } catch(e) {
            alert(e.message);
        }
        
		if (nItem) {
			item.parentNode.insertBefore(item, nItem);
		} else {
			item.parentNode.appendChild(item);
		}
		break;
	case 'gril-delete':
		//TODO: backend
		item.parentNode.removeChild(item);
		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);