less url-building in frontend for sortable tables

This commit is contained in:
Felix Hamann 2018-04-09 23:36:43 +02:00
parent 4896330737
commit 040abcab08
2 changed files with 22 additions and 39 deletions

View File

@ -1,4 +1,4 @@
<table>
<table id="#{dbtIdent}">
$maybe sortableP <- pSortable
$with toSortable <- toSortable sortableP
<thead>

View File

@ -6,32 +6,27 @@
var ASC = 'asc';
var DESC = 'desc';
// TODO: Make use of interpolated dbtIdent
var table = document.querySelector('table');
var ths = Array.from(table.querySelectorAll('th'));
// attach click handler to each table-header
ths.map(function(th) {
th.addEventListener('click', clickHandler);
var link = th.querySelector('a');
if (link) {
link.addEventListener('click', clickHandler);
}
});
// handles click on table header
function clickHandler(event) {
event.preventDefault();
// should instead be smthg like: JSON.parse(this.dataset.sortparams);
// hardcoded for now
var sortParams = {sorting: 'name', prefix: 'terms'};
if (sortParams.order) {
sortParams.order = sortParams.order === ASC ? DESC : ASC;
} else {
sortParams.order = ASC;
}
var params = makeParams(sortParams.prefix, sortParams);
var url = new URL(window.location);
for (var p in params) {
url.searchParams.set(p, params[p]);
}
fetchTableFrom(url);
markSorted(this, sortParams.order);
var url = new URL(window.location.origin + window.location.pathname + this.getAttribute('href'));
var order = this.parentNode.dataset.order || ASC;
// TODO: not working here... getting whole page as response...
url.searchParams.set('table-only', 'true');
updateTableFrom(url);
markSorted(this.parentNode, order);
}
function markSorted(th, order) {
@ -39,40 +34,28 @@
th.classList.remove('sorted-asc', 'sorted-desc');
});
th.classList.add('sorted-' + order);
th.dataset.order = order;
}
// fetches new sorted table from url with params and replaces contents of current table
function fetchTableFrom(url) {
function updateTableFrom(url) {
fetch(url, {
credentials: 'same-origin'
headers: {
'Accept': 'text/html'
}
}).then(function(response) {
var contentType = response.headers.get("content-type");
if (!response.ok) {
throw ('Looks like there was a problem fetching ' + url.toString() + '. Status Code: ' + response.status);
}
// Examine the text in the response
response.text().then(function(data) {
// replace contents of table body
table.querySelector('tbody').innerHTML = data;
});
return response.text();
}).then(function(data) {
// replace contents of table body
table.querySelector('tbody').innerHTML = data;
}).catch(function(err) {
console.error(err);
});
}
// returns default sort-params for with specific prefix
function makeParams(prefix, custom) {
var defaultParams = Object.assign({
pagesize: 20,
page: 0,
order: ASC
}, custom);
var res = {};
for (var p in defaultParams) {
res[prefix + '-' + p] = defaultParams[p];
}
res['table-only'] = 'true';
return res;
}
});
})();