feat(ui): improve the records table, view state and record dialog
Test / test (push) Successful in 26m44s
Build and publish image / image (push) Successful in 27m27s

Sortable record columns, filters and sort kept in the URL on the zones,
zone and audit pages, a Show action that filters the records table to a
problem's owner, Save and add another, a highlight of the saved row, an
Audit history link on the zone page, and dialogs that keep typed input
on a backdrop click.
This commit is contained in:
bryanpedini committed 2026-11-22 17:36:46 +01:00
1 parent a67183b646
commit 440f78ce9e
9 files changed
+419 -36

No files matched your search

+183 -22
View File
@@ -1,23 +1,47 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, appData, busy, clear, clearErrors, confirmDialog, flash, formatTTL, handleError, h, icon, openDialog, option, parseNumber, plural, setupDialogs, showFieldErrors, showFlash, toast, zonePath } from "./common.js";
import { $, api, appData, busy, clear, clearErrors, confirmDialog, flash, formatTTL, handleError, h, icon, openDialog, option, parseNumber, plural, readQuery, setupDialogs, showFieldErrors, showFlash, toast, writeQuery, zonePath } from "./common.js";
import { EDITABLE_TYPES, FIELD_SPECS, displayName, matchesFilter, presentValue, previewName, stripDot } from "./records.js";
const PAGE_SIZE = 100;
const { zone: zoneParam, isAdmin } = appData();
const base = zonePath(zoneParam);
const query = readQuery();
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
function parseSort(text) {
const match = /^(-?)(name|type|ttl|value)$/.exec(text || "");
return match ? { key: match[2], dir: match[1] ? -1 : 1 } : null;
}
const owner = (query.get("name") || "").toLowerCase();
const state = {
summary: null,
records: [],
problems: [],
type: "",
text: "",
type: query.get("type") || "",
text: owner || query.get("q") || "",
owner,
sort: parseSort(query.get("sort")),
page: 0,
pageRows: [],
selected: new Set(),
};
const COMPARE = {
name: (a, b) => collator.compare(a.name, b.name),
type: (a, b) => collator.compare(a.type, b.type),
ttl: (a, b) => (a.ttl || 360) - (b.ttl || 360),
value: (a, b) => collator.compare(displayValue(a), displayValue(b)),
};
function syncUrl() {
writeQuery({ type: state.type, q: state.owner ? "" : state.text.trim(), name: state.owner, sort: state.sort ? (state.sort.dir < 0 ? "-" : "") + state.sort.key : "" });
}
function zoneName() {
return state.summary ? state.summary.name : zoneParam;
}
@@ -40,6 +64,10 @@ function isBroken(record) {
return record.data === null || record.data === undefined || hasErrors(record);
}
function displayValue(record) {
return isBroken(record) ? String(record.raw ?? "") : presentValue(record);
}
function problemBadge(problem) {
return h("li", { class: "problem problem-" + problem.severity },
h("span", { class: "badge badge-" + (problem.severity === "error" ? "error" : "warning"), text: problem.severity }),
@@ -81,6 +109,20 @@ function renderSoa() {
managed.hidden = !dynamic;
}
function showRecords(name, type) {
const apex = zoneName().endsWith(".") ? zoneName() : zoneName() + ".";
state.type = type || "";
state.owner = ((name === "" ? "" : name + ".") + apex).toLowerCase();
state.text = state.owner;
state.page = 0;
typeOptions();
$("#filter-text").value = state.text;
syncUrl();
renderRecords();
$("#records-title").scrollIntoView({ block: "start" });
$("#filter-text").focus();
}
function renderProblems() {
const panel = $("#problems-panel");
const list = $("#problems-list");
@@ -88,9 +130,13 @@ function renderProblems() {
panel.hidden = state.problems.length === 0;
$("#problems-title").textContent = "Problems (" + state.problems.length + ")";
for (const problem of state.problems) {
const where = problem.name === null || problem.name === undefined ? "zone" : (problem.name === "" ? "@" : problem.name) + (problem.type ? " " + problem.type : "");
const located = problem.name !== null && problem.name !== undefined;
const where = located ? (problem.name === "" ? "@" : problem.name) + (problem.type ? " " + problem.type : "") : "zone";
const item = problemBadge(problem);
item.append(" ", h("span", { class: "muted", text: "(" + where + ")" }));
if (located) {
item.append(" ", h("button", { type: "button", class: "btn btn-small btn-link", "aria-label": "Show " + where + " in the records table", text: "Show", onclick: () => showRecords(problem.name, problem.type) }));
}
list.append(item);
}
}
@@ -105,7 +151,24 @@ function typeOptions() {
}
function visibleRecords() {
return state.records.filter((record) => matchesFilter(record, state.type, state.text));
const rows = state.owner
? state.records.filter((record) => (!state.type || record.type === state.type) && (record.fqdn || "").toLowerCase() === state.owner)
: state.records.filter((record) => matchesFilter(record, state.type, state.text));
if (!state.sort) return rows;
const { key, dir } = state.sort;
if (key === "ttl") {
const missing = (record) => !Number.isInteger(record.ttl);
return rows.sort((a, b) => missing(a) - missing(b) || (missing(a) ? 0 : dir * COMPARE.ttl(a, b)));
}
return rows.sort((a, b) => dir * COMPARE[key](a, b));
}
function renderSortHeaders() {
for (const th of document.querySelectorAll("#records-table th[data-sort]")) {
const active = state.sort && state.sort.key === th.dataset.sort;
if (active) th.setAttribute("aria-sort", state.sort.dir > 0 ? "ascending" : "descending");
else th.removeAttribute("aria-sort");
}
}
function problemsCell(record) {
@@ -120,8 +183,10 @@ function renderRecords() {
const pages = Math.max(1, Math.ceil(all.length / PAGE_SIZE));
if (state.page >= pages) state.page = pages - 1;
const rows = all.slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE);
state.pageRows = rows;
clear(body);
for (const record of rows) body.append(recordRow(record));
renderSortHeaders();
const status = $("#records-status");
if (state.records.length === 0) status.textContent = "This zone has no records.";
else if (all.length === 0) status.textContent = "No record matches the filter.";
@@ -152,14 +217,14 @@ function recordRow(record) {
const hasError = hasErrors(record);
const hasWarning = (record.problems || []).length > 0;
const value = h("td", { class: "value" },
h("code", { class: broken ? "mono raw" : "mono", text: broken ? (record.raw ?? "") : presentValue(record) }),
h("code", { class: broken ? "mono raw" : "mono", text: displayValue(record) }),
(record.problems || []).length > 0 ? problemsCell(record) : null);
const edit = h("button", { type: "button", class: "btn btn-small", "aria-label": "Edit " + label, onclick: () => (isSoa ? openSoa(record) : openRecord(record)) }, icon("edit"), " Edit");
const actions = h("td", { class: "actions-cell" }, edit);
if (!isSoa || soaRows().length > 1) {
actions.append(" ", h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Delete " + label, onclick: () => deleteRecord(record) }, icon("trash"), " Delete"));
}
return h("tr", { class: hasError ? "row-error" : hasWarning ? "row-warning" : null },
return h("tr", { class: hasError ? "row-error" : hasWarning ? "row-warning" : null, "data-id": record.id },
h("td", { class: "check" }, checkbox),
h("th", { scope: "row", title: record.fqdn || "" }, h("span", { class: "mono", text: displayName(record) })),
h("td", { text: record.type }),
@@ -168,8 +233,22 @@ function recordRow(record) {
actions);
}
function pageRows() {
return visibleRecords().slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE);
function highlight(id) {
if (id === undefined || id === null || !state.records.some((record) => record.id === id)) return;
const index = visibleRecords().findIndex((record) => record.id === id);
if (index < 0) {
toast("The saved record is hidden by the current filter.");
return;
}
const page = Math.floor(index / PAGE_SIZE);
if (page !== state.page) {
state.page = page;
renderRecords();
}
const row = [...$("#records-body").rows].find((tr) => tr.dataset.id === String(id));
if (!row) return;
row.classList.add("row-flash");
row.scrollIntoView({ block: "nearest" });
}
function updateSelection() {
@@ -178,16 +257,21 @@ function updateSelection() {
const button = $("#bulk-delete");
button.disabled = state.selected.size === 0;
button.textContent = state.selected.size === 0 ? "Delete selected" : "Delete selected (" + state.selected.size + ")";
const selectable = pageRows().filter((record) => record.type !== "SOA");
const selectable = state.pageRows.filter((record) => record.type !== "SOA");
$("#select-all").checked = selectable.length > 0 && selectable.every((record) => state.selected.has(record.id));
}
let loadGeneration = 0;
async function load() {
loadGeneration += 1;
const generation = loadGeneration;
const results = await Promise.allSettled([
api("GET", base),
api("GET", base + "/records"),
api("GET", base + "/check"),
]);
if (generation !== loadGeneration) return;
const [summary, records, check] = results;
if (summary.status === "rejected") {
$("#soa-status").textContent = "The zone could not be loaded.";
@@ -203,6 +287,7 @@ async function load() {
renderSoa();
renderProblems();
typeOptions();
if (records.status === "fulfilled") syncUrl();
renderRecords();
if (isAdmin) loadUsers();
}
@@ -288,6 +373,9 @@ function reportWarnings(message, data) {
const recordForm = {
editing: null,
ttlTouched: false,
another: false,
pending: 0,
session: 0,
};
function fieldId(key) {
@@ -351,6 +439,13 @@ function applyRrsetTtl(result) {
function openRecord(record) {
const form = $("#record-form");
recordForm.session += 1;
form.querySelector(".dialog-body").inert = false;
$("#rec-status").textContent = "";
for (const button of [$("#rec-submit"), $("#rec-submit-another")]) {
button.disabled = false;
button.removeAttribute("aria-busy");
}
const broken = Boolean(record) && isBroken(record);
const known = Boolean(record) && EDITABLE_TYPES.includes(record.type);
recordForm.editing = record || null;
@@ -368,6 +463,7 @@ function openRecord(record) {
form.elements.ttl.value = String(ttl);
buildTypeFields(select.value, record && !broken ? record.data : {});
$("#rec-submit").textContent = record ? "Save changes" : "Add record";
$("#rec-submit-another").hidden = Boolean(record);
updatePreview();
openDialog($("#record-dialog"));
}
@@ -394,27 +490,77 @@ function setupRecordForm() {
buildTypeFields(form.elements.type.value, readTypeValues(form));
if (!recordForm.ttlTouched && !recordForm.editing) updatePreview();
});
const anotherButton = $("#rec-submit-another");
anotherButton.addEventListener("click", () => {
recordForm.another = true;
form.requestSubmit();
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const another = recordForm.another && !recordForm.editing;
recordForm.another = false;
if (recordForm.pending === recordForm.session) return;
clearErrors(form);
if (!form.elements.type.value) {
showFieldErrors(form, { type: "Select a type." });
return;
}
const editing = recordForm.editing;
await busy(form.querySelector("button[type=submit]"), async () => {
try {
const body = recordBody(form);
const result = editing
? await api("PUT", base + "/records/" + editing.id, { body, ifMatch: editing.etag })
: await api("POST", base + "/records", { body });
dialog.close();
const session = recordForm.session;
const fields = form.querySelector(".dialog-body");
const submitButton = $("#rec-submit");
const clicked = another ? anotherButton : submitButton;
const current = () => session === recordForm.session && dialog.open;
let refocus = false;
recordForm.pending = session;
fields.inert = true;
$("#rec-status").textContent = "";
submitButton.disabled = true;
anotherButton.disabled = true;
clicked.setAttribute("aria-busy", "true");
try {
const body = recordBody(form);
const result = editing
? await api("PUT", base + "/records/" + editing.id, { body, ifMatch: editing.etag })
: await api("POST", base + "/records", { body });
const keepOpen = another && current();
if (keepOpen) {
const warnings = result.data && Array.isArray(result.data.warnings) ? result.data.warnings : [];
await load();
if (current()) {
fields.inert = false;
$("#rec-status").textContent = ["Record added.", ...warnings.map((warning) => "Warning: " + warning.message)].join(" ");
buildTypeFields(form.elements.type.value, {});
delete dialog.dataset.dirty;
const first = $("#rec-fields").querySelector("input, select, textarea");
if (first) first.focus();
} else {
reportWarnings("Record added.", result.data);
}
} else {
if (current()) dialog.close();
reportWarnings(editing ? "Record saved." : "Record added.", result.data);
await load();
} catch (err) {
handleError(err, { form, reload: () => { dialog.close(); return load(); } });
if (!dialog.open) highlight(result.data && result.data.record ? result.data.record.id : null);
}
});
} catch (err) {
if (!current()) {
handleError(err, { reload: load });
} else {
fields.inert = false;
handleError(err, { form, reload: () => { dialog.close(); return load(); } });
refocus = true;
}
} finally {
if (recordForm.pending === session) recordForm.pending = 0;
if (session === recordForm.session) {
submitButton.disabled = false;
anotherButton.disabled = false;
clicked.removeAttribute("aria-busy");
fields.inert = false;
if (refocus && dialog.open) (form.querySelector('[aria-invalid="true"]:not(:disabled)') || clicked).focus();
}
}
});
}
@@ -448,16 +594,30 @@ async function bulkDelete() {
}
function setupTable() {
const search = $("#filter-text");
search.value = state.text;
$("#filter-type").addEventListener("change", (event) => {
state.type = event.target.value;
state.page = 0;
syncUrl();
renderRecords();
});
$("#filter-text").addEventListener("input", (event) => {
search.addEventListener("input", (event) => {
state.text = event.target.value;
state.owner = "";
state.page = 0;
renderRecords();
syncUrl();
});
for (const th of document.querySelectorAll("#records-table th[data-sort]")) {
th.querySelector("button").addEventListener("click", () => {
const key = th.dataset.sort;
state.sort = { key, dir: state.sort && state.sort.key === key ? -state.sort.dir : 1 };
state.page = 0;
syncUrl();
renderRecords();
});
}
$("#page-prev").addEventListener("click", () => {
state.page -= 1;
renderRecords();
@@ -467,7 +627,7 @@ function setupTable() {
renderRecords();
});
$("#select-all").addEventListener("change", (event) => {
for (const record of pageRows()) {
for (const record of state.pageRows) {
if (record.type === "SOA") continue;
if (event.target.checked) state.selected.add(record.id);
else state.selected.delete(record.id);
@@ -558,6 +718,7 @@ const exportLink = $("#export-link");
exportLink.href = "/api/v1" + base + "/export";
exportLink.setAttribute("download", "");
$("#import-link").href = "/zones/" + encodeURIComponent(zoneParam) + "/import";
$("#audit-link").href = "/audit?zone=" + encodeURIComponent(zoneParam) + "&kind=change";
setupSoa();
setupRecordForm();
setupTable();