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);