working on filters/sorts

This commit is contained in:
Corban-Lee Jones 2024-07-30 20:39:25 +01:00
parent e8334ec825
commit 3909c08113
5 changed files with 122 additions and 78 deletions

View File

@ -23,6 +23,15 @@ async function ajaxRequest(url, method, data) {
} }
} }
function makeQuerystring(filters, sort) {
let querystring = "?";
console.log(JSON.stringify(filters), null, 4)
for (key in filters) {
querystring += `${key}=${filters[key]}&`;
}
return querystring += `ordering=${sort}`;
}
// Saved Guilds // Saved Guilds
async function getSavedGuilds() { async function getSavedGuilds() {
@ -54,8 +63,9 @@ async function loadChannels(guildId) {
// Subscriptions // Subscriptions
async function getSubscriptions(guildId, page=1, pageSize=10, search="") { async function getSubscriptions(filters, sort) {
const url = `/api/subscription/?guild_id=${guildId}&page=${page}&page_size=${pageSize}&search=${search}`; let querystring = makeQuerystring(filters, sort);
url = `/api/subscription/${querystring}`;
return await ajaxRequest(url, "GET"); return await ajaxRequest(url, "GET");
} }
@ -105,8 +115,9 @@ async function deleteSubChannels(subscriptionId) {
// Filters // Filters
async function getFilters(guildId, page=1, pageSize=10, search="") { async function getFilters(filters, sort) {
const url = `/api/filter/?guild_id=${guildId}&page=${page}&page_size=${pageSize}&search=${search}`; let querystring = makeQuerystring(filters, sort);
url = `/api/filter/${querystring}`;
return await ajaxRequest(url, "GET"); return await ajaxRequest(url, "GET");
} }

View File

@ -172,34 +172,40 @@ $("#filtersTabPane").on("click", ".table-refresh-btn", async function() {
loadFilters(getCurrentlyActiveServer().guild_id); loadFilters(getCurrentlyActiveServer().guild_id);
}); });
async function loadFilters(guildId, page=1, pageSize=null, search=null) { async function loadFilters(guildId) {
if (!guildId) if (!guildId)
return; return;
if (!pageSize) setTableFilter("filtersTable", "guild_id", guildId);
pageSize = $("#filtersTablePageSize").val();
if (!search)
search = $("#filtersTabPane .table-searchbar").val();
$("#filtersTabPane .table-del-btn").prop("disabled", true); $("#filtersTabPane .table-del-btn").prop("disabled", true);
clearExistingFilterRows(); clearExistingFilterRows();
try { try {
const filters = await getFilters(guildId, page, pageSize, search); alert(JSON.stringify(tableFilters["filtersTable"], null, 4))
filtersTable.rows.add(filters.results).draw(false); var contentFilters = await getFilters(tableFilters["filtersTable"], tableSorts["filtersTable"]);
filtersTable.rows.add(contentFilters.results).draw(false);
updateTablePagination("#filtersTabPane .table-pagination", page, pageSize, filters.count, filters.next, filters.previous);
updateTablePaginationInfo("#filtersTabPane .table-page-info", filters.results.length, filters.count);
$("#filtersTable thead .table-select-all").prop("disabled", filters.results.length === 0);
} }
catch (err) { catch (err) {
console.error(err) console.error(err)
console.error(JSON.stringify(err, null, 4)); showToast("danger", `Error Loading Filters: HTTP ${err.status}`, err, 15000);
showToast("danger", `Error Loading Filters: HTTP ${err.status}`, err.responseJSON.message, 15000); return;
} }
// shorthand
let filters = tableFilters["filtersTable"];
updateTablePagination(
"#filtersTabPane .table-pagination",
filters["page"], filters["page_size"], contentFilters.count, contentFilters.next, contentFilters.previous
);
updateTablePaginationInfo(
"#filtersTabPane .table-page-info",
contentFilters.results.length, contentFilters.count
);
$("#filtersTable thead .table-select-all").prop("disabled", contentFilters.results.length === 0);
console.debug(`loaded filters, ${contentFilters.results.length} found`);
} }
$(document).ready(async function() { $(document).ready(async function() {

View File

@ -11,6 +11,7 @@ async function initSubscriptionTable() {
subTable = $("#subTable").DataTable({ subTable = $("#subTable").DataTable({
info: false, info: false,
paging: false, paging: false,
ordering: false,
searching: false, searching: false,
autoWidth: false, autoWidth: false,
order: [], order: [],
@ -60,18 +61,10 @@ async function initSubscriptionTable() {
return `<span class="badge text-bg-secondary">${data}</span>`; return `<span class="badge text-bg-secondary">${data}</span>`;
} }
}, },
// {
// title: "Content",
// data: "channels_count",
// render: function(data, type) {
// }
// },
{ {
title: "Created", title: "Created",
data: "creation_datetime", data: "creation_datetime",
render: function(data, type) { render: function(data, type) {
// return new Date(data).toISOString().split("T")[0];
let dateTime = new Date(data); let dateTime = new Date(data);
let dateTimeString = formatDate(dateTime); let dateTimeString = formatDate(dateTime);
return $(` return $(`
@ -341,35 +334,37 @@ $("#subscriptionsTabPane").on("click", ".table-refresh-btn", async function() {
loadSubscriptions(getCurrentlyActiveServer().guild_id); loadSubscriptions(getCurrentlyActiveServer().guild_id);
}); });
async function loadSubscriptions(guildId, page=1, pageSize=null, search=null) { async function loadSubscriptions(guildId) {
if (!guildId)
if (!guildId)
return; return;
if (!pageSize) setTableFilter("subTable", "guild_id", guildId);
pageSize = $("#subTablePageSize").val();
if (!search)
search = $("#subscriptionsTabPane .table-searchbar").val();
$("#subscriptionsTabPane .table-del-btn").prop("disabled", true); $("#subscriptionsTabPane .table-del-btn").prop("disabled", true);
clearExistingSubRows(); clearExistingSubRows();
try { try {
const subscriptions = await getSubscriptions(guildId, page, pageSize, search); alert(JSON.stringify(tableFilters["subTable"], null, 4))
subTable.rows.add(subscriptions.results).draw(false); var subs = await getSubscriptions(tableFilters["subTable"], tableSorts["subTable"]);
subTable.rows.add(subs.results).draw(false);
updateTablePagination("#subscriptionsTabPane .table-pagination", page, pageSize, subscriptions.count, subscriptions.next, subscriptions.previous);
updateTablePaginationInfo("#subscriptionsTabPane .table-page-info", subscriptions.results.length, subscriptions.count);
$("#subTable thead .table-select-all").prop("disabled", subscriptions.results.length === 0);
console.debug("loading subs, " + subscriptions.results.length + " found");
} }
catch (err) { catch (err) {
console.error(err) console.error(err)
console.error(JSON.stringify(err, null, 4)); showToast("danger", `Error Loading Subscriptions: HTTP ${err.status}`, err, 15000);
showToast("danger", `Error Loading Subscriptions: HTTP ${err.status}`, err.responseJSON.message, 15000); return;
} }
updateTableContainer(
tableFilters["subTable"]["page"],
tableFilters["subTable"]["page_size"],
subs.results.length,
subs.count,
subs.next,
subs.previous
);
$("#subTable thead .table-select-all").prop("disabled", subs.results.length === 0);
console.debug("loading subs, " + subs.results.length + " found");
} }
// #region Server Change Event Handler // #region Server Change Event Handler

View File

@ -1,4 +1,23 @@
var timeouts = {}; var timeouts = {};
tableFilters = {};
tableSorts = {};
$(document).on("selectedServerChange", async function() {
// Clear filters and sorts when changing server
tableFilters = {};
tableSorts = {};
})
function setTableFilter(tableId, key, value) {
if (!tableFilters[tableId])
tableFilters[tableId] = {}
tableFilters[tableId][key] = value;
}
function setTableSorts(tableId, value) {
tableSorts[tableId] = value;
}
async function initTable(containingSelector, tableId, loadDataFunc, newRowFunc, deleteSelectedFunc, options=null) { async function initTable(containingSelector, tableId, loadDataFunc, newRowFunc, deleteSelectedFunc, options=null) {
let pageSizeId = tableId + "PageSize"; let pageSizeId = tableId + "PageSize";
@ -10,11 +29,11 @@ async function initTable(containingSelector, tableId, loadDataFunc, newRowFunc,
createTable(containingSelector, tableId); createTable(containingSelector, tableId);
createTableControls(containingSelector, pageSizeId); createTableControls(containingSelector, pageSizeId);
await bindSearchBar(searchId, loadDataFunc); await bindSearchBar(tableId, searchId, loadDataFunc);
// await bindSortDropdown(sortDropdownId, loadDataFunc); await bindSortDropdown(tableId, sortDropdownId, loadDataFunc);
await bindFilterDropdown(filterDropdownId, loadDataFunc); await bindFilterDropdown(tableId, filterDropdownId, loadDataFunc);
await bindTablePagination(`${containingSelector} .table-pagination`, loadDataFunc); await bindTablePagination(tableId, `${containingSelector} .table-pagination`, loadDataFunc);
await bindTablePaginationResizer(`${containingSelector} .table-page-sizer`, loadDataFunc); await bindTablePaginationResizer(tableId, `${containingSelector} .table-page-sizer`, loadDataFunc);
} }
function createSearchRow(containingSelector, searchId, sortDropdownId, filterDropdownId, options, newRowFunc, deleteSelectedFunc) { function createSearchRow(containingSelector, searchId, sortDropdownId, filterDropdownId, options, newRowFunc, deleteSelectedFunc) {
@ -38,6 +57,7 @@ function createSearchRow(containingSelector, searchId, sortDropdownId, filterDro
</div> </div>
`); `);
// If there is a function that allows the creation of new rows, create a button for it
if (newRowFunc) { if (newRowFunc) {
$(`${containingSelector} .table-search-row .table-search-buttons`).prepend(` $(`${containingSelector} .table-search-row .table-search-buttons`).prepend(`
<div class="d-inline-block ms-3"> <div class="d-inline-block ms-3">
@ -49,6 +69,7 @@ function createSearchRow(containingSelector, searchId, sortDropdownId, filterDro
$(`${containingSelector} .table-search-row .table-search-buttons .table-new-btn`).on("click", async () => {await newRowFunc(-1)}); $(`${containingSelector} .table-search-row .table-search-buttons .table-new-btn`).on("click", async () => {await newRowFunc(-1)});
} }
// Show the sort dropdown
if (options.sort) { if (options.sort) {
$(`${containingSelector} .table-search-row .table-search-buttons`).append(` $(`${containingSelector} .table-search-row .table-search-buttons`).append(`
<div class="d-inline-block ms-3"> <div class="d-inline-block ms-3">
@ -66,6 +87,7 @@ function createSearchRow(containingSelector, searchId, sortDropdownId, filterDro
// bindSortDropdown(sortDropdownId); // bindSortDropdown(sortDropdownId);
} }
// Show the filters dropdown
if (options.filter && options.actions.GET) { if (options.filter && options.actions.GET) {
$(`${containingSelector} .table-search-row .table-search-buttons`).append(` $(`${containingSelector} .table-search-row .table-search-buttons`).append(`
<div class="d-inline-block ms-3"> <div class="d-inline-block ms-3">
@ -82,6 +104,7 @@ function createSearchRow(containingSelector, searchId, sortDropdownId, filterDro
populateFilterDropdown(filterDropdownId, options.actions.GET, options.filter); populateFilterDropdown(filterDropdownId, options.actions.GET, options.filter);
} }
// If there is a function for deleting selected rows, create a button for it
if (deleteSelectedFunc) { if (deleteSelectedFunc) {
$(`${containingSelector} .table-search-row .table-search-buttons`).append(` $(`${containingSelector} .table-search-row .table-search-buttons`).append(`
<div class="d-inline-block ms-3"> <div class="d-inline-block ms-3">
@ -143,11 +166,18 @@ function populateFilterDropdown(filterDropdownId, options, filterKeys) {
$(`#${filterDropdownId} .dropdown-menu`).append($("<li>").append($elem)); $(`#${filterDropdownId} .dropdown-menu`).append($("<li>").append($elem));
} }
// Reset the controls
$(document).on("selectedServerChange", async function() {
$(`#${filterDropdownId} .dropdown-menu input[type="checkbox"]`).each(function() {
$(this).data("state", null);
updateCheckboxState($(this).parent());
});
});
} }
function bindFilterBoolean($elem) { function bindFilterBoolean($elem) {
$elem.find('label').on("click", function(event) { $elem.find('label').on("click", function() {
event.preventDefault();
let $input = $elem.find('input[type="checkbox"]'); let $input = $elem.find('input[type="checkbox"]');
let state = $input.data("state"); let state = $input.data("state");
@ -190,20 +220,29 @@ function updateCheckboxState($elem) {
} }
} }
async function bindSearchBar(searchBarSelector, loadDataFunc) { async function bindSearchBar(tableId, searchBarSelector, loadDataFunc) {
searchBar = $("#" + searchBarSelector) searchBar = $("#" + searchBarSelector)
searchBar.on("input", async function() { searchBar.on("input", async function() {
clearTimeout(timeouts[searchBarSelector]); clearTimeout(timeouts[searchBarSelector]);
var searchString = $(this).val(); var searchString = $(this).val();
setTableFilter(tableId, "search", searchString);
timeouts[searchBarSelector] = setTimeout(async function() { timeouts[searchBarSelector] = setTimeout(async function() {
await loadDataFunc(getCurrentlyActiveServer().guild_id, 1, null, searchString); await loadDataFunc(getCurrentlyActiveServer().guild_id);
}, 300); }, 300);
}); });
} }
async function bindFilterDropdown(filterDropdownId, loadDataFunc) { async function bindFilterDropdown(tableId, filterDropdownId, loadDataFunc) {
$(`#${filterDropdownId} input`).on("change", function() { $(`#${filterDropdownId} .dropdown-menu`).on("change", "input", async function() {
alert($(this).attr("data-key")); setTableFilter(tableId, $(this).attr("data-key"), $(this).data("state"));
await loadDataFunc(getCurrentlyActiveServer().guild_id);
});
}
async function bindSortDropdown(tableId, sortDropdownId, loadDataFunc) {
$(`#${sortDropdownId} .dropdown-menu`).on("click", "button", async function() {
setTableSorts(tableId, $(this).attr("data-sortkey"))
await loadDataFunc(getCurrentlyActiveServer().guild_id);
}); });
} }
@ -259,6 +298,11 @@ function createTableControls(containingSelector, pageSizeId) {
}); });
} }
function updateTableContainer(containerSelector, page, pageSize, itemsCount, totalItemsCount, nextExists, prevExists) {
updateTablePagination(containerSelector, page, pageSize, totalItemsCount, nextExists, prevExists);
updateTablePaginationInfo(containerSelector, itemsCount, totalItemsCount);
}
// Updates the pagination text for a given pageInfoId // Updates the pagination text for a given pageInfoId
function updateTablePaginationInfo(pageInfoId, showing, total) { function updateTablePaginationInfo(pageInfoId, showing, total) {
$(`${pageInfoId} .pageinfo-showing`).text(showing); $(`${pageInfoId} .pageinfo-showing`).text(showing);
@ -345,7 +389,7 @@ function addEllipsis(pageControlsId) {
} }
// Bind the table pagination buttons to control the table pagination // Bind the table pagination buttons to control the table pagination
async function bindTablePagination(pageControlsId, dataLoadFunc) { async function bindTablePagination(tableId, pageControlsId, dataLoadFunc) {
$(`${pageControlsId} .pagination`).on("click", ".page-link", async function() { $(`${pageControlsId} .pagination`).on("click", ".page-link", async function() {
let wantedPage; let wantedPage;
let currentPage = parseInt($(pageControlsId).attr("data-page")); let currentPage = parseInt($(pageControlsId).attr("data-page"));
@ -357,17 +401,18 @@ async function bindTablePagination(pageControlsId, dataLoadFunc) {
else else
wantedPage = $(this).attr("data-page"); wantedPage = $(this).attr("data-page");
await dataLoadFunc(getCurrentlyActiveServer().guild_id, wantedPage) setTableFilter(tableId, "page", wantedPage);
await dataLoadFunc(getCurrentlyActiveServer().guild_id)
}); });
} }
// Bind the table pagination page resizer control // Bind the table pagination page resizer control
async function bindTablePaginationResizer(resizerControlId, dataLoadFunc) { async function bindTablePaginationResizer(tableId, resizerControlId, dataLoadFunc) {
$(resizerControlId).on("change", async function() { $(resizerControlId).on("change", async function() {
const page = 1; setTableFilter(tableId, "page", 1);
const pageSize = $(this).val(); setTableFilter(tableId, "page_size", $(this).val());
await dataLoadFunc(getCurrentlyActiveServer().guild_id, page, pageSize); await dataLoadFunc(getCurrentlyActiveServer().guild_id);
}); });
} }

View File

@ -2,7 +2,7 @@
<div class="row my-3 px-3"> <div class="row my-3 px-3">
<div class="col-12 text-end"> <div class="col-12 text-end">
<button type="submit" id="saveSettings" class="btn btn-primary rounded-1">Save Changes</button> <button type="submit" id="saveSettings" class="btn btn-primary rounded-1">Save Changes</button>
<button type="button" class="btn btn-outline-danger">Reset All</button> <button type="button" class="btn btn-outline-danger rounded-1 ms-3">Reset All</button>
</div> </div>
</div> </div>
<div class="row my-3 px-3"> <div class="row my-3 px-3">
@ -27,17 +27,4 @@
</div> </div>
</div> </div>
</div> </div>
<!-- <div class="row px-3">
<div class="col-lg-4">
<div class="colour-input"
data-id="defaultEmbedColour"
data-label="Default Embed Colour"
data-helptext="Default colour of each embed in Discord."
data-defaultcolour="#3498db">
</div>
</div>
<div class="col-12 text-end">
<button type="submit" id="saveSettings" class="btn btn-primary rounded-1">Save Changes</button>
</div>
</div> -->
</form> </form>