303 lines
10 KiB
JavaScript
303 lines
10 KiB
JavaScript
/**
|
|
* Generic list page engine.
|
|
*
|
|
* Reads the resource slug from <body data-resource="...">, looks up its
|
|
* schema in Resources and renders a DaisyUI table with server-side
|
|
* pagination, sorting and search, plus loading / empty / error states.
|
|
*/
|
|
(function () {
|
|
"use strict";
|
|
|
|
const PAGE_SIZE = 10;
|
|
|
|
document.addEventListener("DOMContentLoaded", () => {
|
|
const body = document.body;
|
|
if (body.dataset.page !== "list") return;
|
|
if (!Auth.requireAuth()) return;
|
|
|
|
const slug = body.dataset.resource;
|
|
const schema = Resources[slug];
|
|
if (!schema) return;
|
|
|
|
const els = {
|
|
head: document.getElementById("list-head"),
|
|
body: document.getElementById("list-body"),
|
|
state: document.getElementById("list-state"),
|
|
search: document.getElementById("list-search"),
|
|
pagination: document.getElementById("list-pagination"),
|
|
parentWrap: document.getElementById("list-parent-filter"),
|
|
parentSelect: document.getElementById("list-parent-select"),
|
|
count: document.getElementById("list-count"),
|
|
};
|
|
|
|
const state = {
|
|
page: 1,
|
|
limit: PAGE_SIZE,
|
|
search: "",
|
|
sort: "",
|
|
order: "desc",
|
|
parentId: null,
|
|
};
|
|
|
|
const columnCount = schema.columns.length + 1; // + actions
|
|
|
|
// ----- rendering helpers -------------------------------------------------
|
|
|
|
function renderHead() {
|
|
const cells = schema.columns
|
|
.map((column) => {
|
|
if (!column.sortKey) {
|
|
return `<th scope="col">${UI.escapeHtml(column.label)}</th>`;
|
|
}
|
|
const isActive = state.sort === column.sortKey;
|
|
const arrow = !isActive ? "" : state.order === "asc" ? " ▲" : " ▼";
|
|
return (
|
|
`<th scope="col"><button type="button" class="inline-flex items-center gap-1 font-semibold hover:text-primary" ` +
|
|
`data-sort="${column.sortKey}" aria-label="Sort by ${UI.escapeHtml(column.label)}">` +
|
|
`${UI.escapeHtml(column.label)}${arrow}</button></th>`
|
|
);
|
|
})
|
|
.join("");
|
|
els.head.innerHTML = `<tr>${cells}<th scope="col" class="text-right">Actions</th></tr>`;
|
|
|
|
els.head.querySelectorAll("[data-sort]").forEach((button) => {
|
|
button.addEventListener("click", () => {
|
|
const key = button.dataset.sort;
|
|
if (state.sort === key) {
|
|
state.order = state.order === "asc" ? "desc" : "asc";
|
|
} else {
|
|
state.sort = key;
|
|
state.order = "asc";
|
|
}
|
|
state.page = 1;
|
|
load();
|
|
});
|
|
});
|
|
}
|
|
|
|
function cellHtml(column, row) {
|
|
const value = row[column.key];
|
|
switch (column.type) {
|
|
case "id":
|
|
return `<td class="font-mono text-xs">${UI.escapeHtml(value)}</td>`;
|
|
case "lang":
|
|
return `<td class="max-w-xs truncate" title="${UI.escapeHtml(langText(value))}">${UI.escapeHtml(langText(value))}</td>`;
|
|
case "image":
|
|
return value
|
|
? `<td><img src="${UI.escapeHtml(value)}" alt="" class="h-10 w-16 rounded object-cover" loading="lazy"></td>`
|
|
: `<td><span class="text-base-content/40">—</span></td>`;
|
|
case "date":
|
|
return `<td class="whitespace-nowrap">${UI.escapeHtml(UI.formatDate(value))}</td>`;
|
|
case "bool":
|
|
if (schema.statusToggle) {
|
|
return (
|
|
`<td><input type="checkbox" class="toggle toggle-primary toggle-sm" data-status-toggle ` +
|
|
`${value ? "checked" : ""} aria-label="Toggle status"></td>`
|
|
);
|
|
}
|
|
return `<td>${value ? '<span class="badge badge-success badge-sm">Active</span>' : '<span class="badge badge-ghost badge-sm">Inactive</span>'}</td>`;
|
|
default:
|
|
return `<td class="max-w-xs truncate" title="${UI.escapeHtml(value)}">${UI.escapeHtml(value)}</td>`;
|
|
}
|
|
}
|
|
|
|
function renderRows(rows) {
|
|
els.body.innerHTML = "";
|
|
rows.forEach((row) => {
|
|
const tr = document.createElement("tr");
|
|
tr.className = "hover";
|
|
tr.innerHTML =
|
|
schema.columns.map((column) => cellHtml(column, row)).join("") +
|
|
`<td class="text-right whitespace-nowrap">
|
|
<a class="btn btn-ghost btn-xs" href="/admin/${slug}/${row.Id}/edit" aria-label="Edit item ${row.Id}">Edit</a>
|
|
<button type="button" class="btn btn-ghost btn-xs text-error" data-delete aria-label="Delete item ${row.Id}">Delete</button>
|
|
</td>`;
|
|
|
|
const toggle = tr.querySelector("[data-status-toggle]");
|
|
if (toggle) {
|
|
toggle.addEventListener("change", async () => {
|
|
toggle.disabled = true;
|
|
try {
|
|
await Api.put(
|
|
`${schema.endpoint}/${row.Id}/status?status=${toggle.checked}`
|
|
);
|
|
UI.toast("Status updated", "success");
|
|
} catch (error) {
|
|
toggle.checked = !toggle.checked;
|
|
UI.toast(error.message, "error");
|
|
} finally {
|
|
toggle.disabled = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
tr.querySelector("[data-delete]").addEventListener("click", async () => {
|
|
const confirmed = await UI.confirm({
|
|
title: "Delete item",
|
|
message: `Delete this ${schema.title.toLowerCase().replace(/s$/, "")}? This action cannot be undone.`,
|
|
});
|
|
if (!confirmed) return;
|
|
try {
|
|
await Api.del(`${schema.endpoint}/${row.Id}`);
|
|
UI.toast("Deleted successfully", "success");
|
|
load();
|
|
} catch (error) {
|
|
UI.toast(error.message, "error");
|
|
}
|
|
});
|
|
|
|
els.body.appendChild(tr);
|
|
});
|
|
}
|
|
|
|
function renderState(html) {
|
|
els.body.innerHTML = "";
|
|
els.state.innerHTML = html;
|
|
els.state.classList.remove("hidden");
|
|
}
|
|
|
|
function renderLoading() {
|
|
els.state.classList.add("hidden");
|
|
els.body.innerHTML = Array.from({ length: 5 })
|
|
.map(
|
|
() =>
|
|
`<tr>${Array.from({ length: columnCount })
|
|
.map(() => '<td><div class="skeleton h-4 w-full"></div></td>')
|
|
.join("")}</tr>`
|
|
)
|
|
.join("");
|
|
}
|
|
|
|
function renderPagination(count) {
|
|
const totalPages = Math.max(1, Math.ceil(count / state.limit));
|
|
if (state.page > totalPages) {
|
|
state.page = totalPages;
|
|
}
|
|
els.pagination.innerHTML = `
|
|
<div class="join">
|
|
<button type="button" class="join-item btn btn-sm" data-page-prev ${state.page <= 1 ? "disabled" : ""} aria-label="Previous page">«</button>
|
|
<button type="button" class="join-item btn btn-sm no-animation" tabindex="-1">Page ${state.page} of ${totalPages}</button>
|
|
<button type="button" class="join-item btn btn-sm" data-page-next ${state.page >= totalPages ? "disabled" : ""} aria-label="Next page">»</button>
|
|
</div>`;
|
|
const prev = els.pagination.querySelector("[data-page-prev]");
|
|
const next = els.pagination.querySelector("[data-page-next]");
|
|
prev.addEventListener("click", () => {
|
|
state.page -= 1;
|
|
load();
|
|
});
|
|
next.addEventListener("click", () => {
|
|
state.page += 1;
|
|
load();
|
|
});
|
|
}
|
|
|
|
// ----- data loading ------------------------------------------------------
|
|
|
|
function listUrl() {
|
|
return schema.listUrl ? schema.listUrl(state) : schema.endpoint;
|
|
}
|
|
|
|
async function load() {
|
|
if (schema.parentFilter && !state.parentId) {
|
|
renderState(
|
|
`<div class="py-10 text-center text-base-content/60">Create a category first, then add sub-categories to it.</div>`
|
|
);
|
|
els.pagination.innerHTML = "";
|
|
return;
|
|
}
|
|
|
|
renderLoading();
|
|
try {
|
|
const data = await Api.get(listUrl(), {
|
|
limit: state.limit,
|
|
page: state.page,
|
|
search: state.search,
|
|
sort: state.sort,
|
|
order: state.order,
|
|
});
|
|
const rows = (data && data[schema.listKey]) || [];
|
|
const count = (data && data.count) || 0;
|
|
|
|
if (els.count) {
|
|
els.count.textContent = count + " total";
|
|
}
|
|
|
|
if (!rows.length) {
|
|
renderState(
|
|
`<div class="py-10 text-center text-base-content/60">
|
|
<p class="mb-3">Nothing here yet${state.search ? " for “" + UI.escapeHtml(state.search) + "”" : ""}.</p>
|
|
<a href="/admin/${slug}/new" class="btn btn-primary btn-sm">Create the first one</a>
|
|
</div>`
|
|
);
|
|
} else {
|
|
els.state.classList.add("hidden");
|
|
renderRows(rows);
|
|
}
|
|
renderHead();
|
|
renderPagination(count);
|
|
} catch (error) {
|
|
renderState(
|
|
`<div class="py-10 text-center">
|
|
<p class="mb-3 text-error">${UI.escapeHtml(error.message)}</p>
|
|
<button type="button" class="btn btn-outline btn-sm" data-retry>Retry</button>
|
|
</div>`
|
|
);
|
|
els.pagination.innerHTML = "";
|
|
els.state
|
|
.querySelector("[data-retry]")
|
|
.addEventListener("click", () => load());
|
|
}
|
|
}
|
|
|
|
async function initParentFilter() {
|
|
if (!schema.parentFilter) return;
|
|
els.parentWrap.classList.remove("hidden");
|
|
try {
|
|
const data = await Api.get(schema.parentFilter.endpoint, {
|
|
limit: 0,
|
|
page: 0,
|
|
});
|
|
const items = (data && data[schema.parentFilter.listKey]) || [];
|
|
els.parentSelect.innerHTML = items
|
|
.map(
|
|
(item) =>
|
|
`<option value="${item.Id}">${UI.escapeHtml(langText(item[schema.parentFilter.labelField]))}</option>`
|
|
)
|
|
.join("");
|
|
if (items.length) {
|
|
state.parentId = items[0].Id;
|
|
els.parentSelect.value = String(state.parentId);
|
|
}
|
|
els.parentSelect.addEventListener("change", () => {
|
|
state.parentId = Number(els.parentSelect.value);
|
|
state.page = 1;
|
|
load();
|
|
});
|
|
} catch (error) {
|
|
UI.toast(error.message, "error");
|
|
}
|
|
}
|
|
|
|
// ----- search ------------------------------------------------------------
|
|
|
|
if (els.search) {
|
|
let debounce;
|
|
els.search.addEventListener("input", () => {
|
|
clearTimeout(debounce);
|
|
debounce = setTimeout(() => {
|
|
state.search = els.search.value.trim();
|
|
state.page = 1;
|
|
load();
|
|
}, 350);
|
|
});
|
|
}
|
|
|
|
// ----- init ----------------------------------------------------------------
|
|
|
|
renderHead();
|
|
Auth.loadProfile();
|
|
Auth.bindLogoutButtons();
|
|
initParentFilter().then(load);
|
|
});
|
|
})();
|