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 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, getCurrentOrder(item.id) - 1); } catch(e) { alert(e.message); } item.parentNode.insertBefore(item, pItem); break; case 'gril-sort-down': try { await updateGrilOrder(item.id, getCurrentOrder(item.id) + 1); } catch(e) { alert(e.message); } if (nItem) { item.parentNode.insertBefore(item, nItem); } else { item.parentNode.appendChild(item); } break; case 'gril-delete': let liFilter = x => x.tagName && x.tagName.toLowerCase() === 'li'; let item = dom.closest(e.target, liFilter); try { await ajax.del( `${window.location}/order`, `gril=${item.id}`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }); item.parentNode.removeChild(item); } 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);