viewof pages = {
function clickedCol() {
let currentReverse = false;
let thisCol;
d3.selectAll("th span")._groups[0].forEach((d, i) => {
if (d.innerHTML) {
thisCol = d.nextSibling.data;
currentReverse = d.innerHTML === "▴" ? false : true;
}
});
return [thisCol, currentReverse];
}
const rowsPerPage = page_settings.rowsPerPage + 1;
const numPagesGeneral = Math.ceil(search.length / rowsPerPage);
const numPages = (search.length <= (numPagesGeneral - 1) * rowsPerPage) ? numPagesGeneral - 1 : numPagesGeneral;
const element = html`<div id="pgDiv" style="display: inline-block;">
${Array.from({ length: numPages }).map(
(_, i) => {
let thisClass = i === 0 ? "btnactive" : "pgbtn"
return html`<button action="page" id="pg${i}" class=${thisClass}>${i + 1}</button>`;
}
)}
</div>`;
const initSortCol = "Salary paid"
const initSortReverse = false;
element.value = [search,
initSortCol,
initSortReverse, // initially sort ascending
];
// Define button click event
element.onclick = (d) => {
// Store id of previous and currently clicked button
const prevClicked = d3.select(".btnactive").attr("id");
const nowClicked = d.target.id;
// Get action label from button div
// For later, to distiguish between page buttons and "Previous", "Next" and "Last" buttons
// when they get set up
let thisAction = d3.select(`#${d.target.id}`).attr("action");
// Handle Previous and Next buttons separately
if (thisAction === "page") {
if (nowClicked === prevClicked) {
return; // do nothing if button now clicked is already clicked
} else {
// Get name of column that table is sorted by (initally "Salary paid")
let thisCol = clickedCol()[0];
// Get sort direction
let currentReverse = clickedCol()[1];
// Page clicked
let thisPg = parseInt(d.target.id.split("pg")[1]);
// Deactivate previously clicked button & activate current button
d3.select(`#${prevClicked}`).attr("class", "pgbtn");
d3.select(`#${nowClicked}`).attr("class", "btnactive");
// Define starting row of data array for selected page
let lim0 = thisPg * (rowsPerPage);
// Define end row of data array for selected page. If end row
// is > length of array, stop at length of array.
let lim1 = lim0 + rowsPerPage - 1; //(lim0 + rowsPerPage) > search.length ? search.length : lim0 + rowsPerPage;
// Assign row limits to returned array
let sortedSearch = {};
if (typeof search[0][thisCol] == "string") {
sortedSearch = currentReverse ?
search.sort((a, b) => (a["First name"] < b["First name"] ? 1 : -1)) :
search.sort((a, b) => (a["First name"] > b["First name"] ? 1 : -1))
} else if (typeof search[0][thisCol] == "number") {
sortedSearch = currentReverse ?
search.sort((a, b) => b[thisCol] - a[thisCol]) :
search.sort((a, b) => a[thisCol] - b[thisCol]);
}
// Set up return values in array
element.value = [d.target.id === "pg0" ? sortedSearch : sortedSearch.slice(lim0, lim1), // returned, sorted page data
thisCol, // col to sort by
currentReverse, // sort direction
];
}
}
element.dispatchEvent(new Event("input", {bubbles: true}));
};
return element;
}