Files
bryanpedini 440f78ce9e
Test / test (push) Successful in 26m44s
Build and publish image / image (push) Successful in 27m27s
feat(ui): improve the records table, view state and record dialog
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.
2026-11-22 17:36:46 +01:00

727 lines
28 KiB
JavaScript

// 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, 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: 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;
}
function soaRows() {
return state.records.filter((record) => record.type === "SOA");
}
function soaRow() {
const rows = soaRows();
const summary = state.summary && state.summary.soa ? rows.find((record) => record.id === state.summary.soa.id) : null;
return summary || rows.find((record) => record.name === "") || rows[0] || null;
}
function hasErrors(record) {
return (record.problems || []).some((problem) => problem.severity === "error");
}
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 }),
" ",
h("code", { text: problem.code }),
" ",
problem.message);
}
function renderSoa() {
const summary = $("#soa-summary");
const status = $("#soa-status");
const managed = $("#soa-managed");
const edit = $("#soa-edit");
clear(summary);
managed.hidden = true;
const soa = state.summary ? state.summary.soa : null;
const count = soaRows().length;
edit.disabled = count === 0;
if (!soa) {
status.textContent = count === 0 ? "This zone has no SOA record." : count > 1 ? "This zone has " + count + " SOA records. Delete the extra ones in the records table and edit the one to keep." : "The SOA record has errors. Edit it to repair it.";
return;
}
status.textContent = count > 1 ? "This zone has " + count + " SOA records. Delete the extra ones in the records table." : "";
const dynamic = soa.serial === null || soa.serial === undefined;
const items = [
["Primary name server", soa.ns],
["Hostmaster", soa.mbox],
["Serial", dynamic ? "dynamic (Unix time)" : String(soa.serial)],
["Refresh", String(soa.refresh)],
["Retry", String(soa.retry)],
["Expire", String(soa.expire)],
["Minimum TTL", String(soa.minttl)],
["TTL", formatTTL(soa.ttl)],
];
for (const [term, value] of items) {
summary.append(h("dt", { text: term }), h("dd", { class: "mono", text: value }));
}
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");
clear(list);
panel.hidden = state.problems.length === 0;
$("#problems-title").textContent = "Problems (" + state.problems.length + ")";
for (const problem of state.problems) {
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);
}
}
function typeOptions() {
const select = $("#filter-type");
const types = [...new Set(state.records.map((record) => record.type))].sort();
if (state.type && !types.includes(state.type)) state.type = "";
clear(select);
select.append(option("", "All types", state.type === ""));
for (const type of types) select.append(option(type, type, state.type === type));
}
function visibleRecords() {
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) {
const list = h("ul", { class: "problems" });
for (const problem of record.problems || []) list.append(problemBadge(problem));
return list;
}
function renderRecords() {
const body = $("#records-body");
const all = visibleRecords();
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.";
else status.textContent = plural(all.length, "record", "records") + (all.length === state.records.length ? "." : " of " + state.records.length + ".");
const pager = $("#pager");
pager.hidden = all.length <= PAGE_SIZE;
$("#page-info").textContent = "Page " + (state.page + 1) + " of " + pages;
$("#page-prev").disabled = state.page === 0;
$("#page-next").disabled = state.page >= pages - 1;
updateSelection();
}
function recordRow(record) {
const label = displayName(record) + " " + record.type;
const broken = isBroken(record);
const isSoa = record.type === "SOA";
const checkbox = h("input", {
type: "checkbox",
disabled: isSoa,
checked: state.selected.has(record.id),
"aria-label": "Select " + label,
onchange: (event) => {
if (event.target.checked) state.selected.add(record.id);
else state.selected.delete(record.id);
updateSelection();
},
});
const hasError = hasErrors(record);
const hasWarning = (record.problems || []).length > 0;
const value = h("td", { class: "value" },
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, "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 }),
h("td", { class: "num", text: formatTTL(record.ttl) }),
value,
actions);
}
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() {
const ids = new Set(state.records.map((record) => record.id));
for (const id of state.selected) if (!ids.has(id)) state.selected.delete(id);
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 = 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.";
$("#records-status").textContent = "The records could not be loaded.";
handleError(summary.reason);
return;
}
state.summary = summary.value.data;
state.records = records.status === "fulfilled" ? records.value.data.records || [] : [];
state.problems = check.status === "fulfilled" ? check.value.data.problems || [] : [];
if (records.status === "rejected") handleError(records.reason);
$("#zone-title").textContent = state.summary.name;
renderSoa();
renderProblems();
typeOptions();
if (records.status === "fulfilled") syncUrl();
renderRecords();
if (isAdmin) loadUsers();
}
function numberFields(form, names) {
const out = {};
for (const name of names) out[name] = parseNumber(form.elements[name].value);
return out;
}
function soaBody(form) {
return {
ns: form.elements.ns.value.trim(),
mbox: form.elements.mbox.value.trim(),
...numberFields(form, ["ttl", "refresh", "retry", "expire", "minttl"]),
};
}
const soaForm = { etag: null };
function soaValues(record) {
const summary = state.summary ? state.summary.soa : null;
if (summary && record && summary.id === record.id && !hasErrors(record)) return summary;
const ttl = record && Number.isInteger(record.ttl) && record.ttl >= 0 ? record.ttl : 3600;
if (record && !isBroken(record)) {
const data = record.data;
return { ns: data.ns, mbox: data.MBox !== undefined ? data.MBox : data.mbox, ttl, refresh: data.refresh, retry: data.retry, expire: data.expire, minttl: data.minttl };
}
return { ns: "", mbox: "", ttl, refresh: 3600, retry: 600, expire: 604800, minttl: 300 };
}
function openSoa(selected) {
const form = $("#soa-form");
const record = selected || soaRow();
soaForm.etag = record ? record.etag : null;
$("#soa-broken").hidden = !record || !isBroken(record);
const values = soaValues(record);
for (const name of ["ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"]) form.elements[name].value = values[name] === undefined || values[name] === null ? "" : String(values[name]);
openDialog($("#soa-dialog"));
}
function setupSoa() {
const dialog = $("#soa-dialog");
const form = $("#soa-form");
$("#soa-edit").addEventListener("click", () => openSoa(null));
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
const etag = soaForm.etag;
await busy(form.querySelector("button[type=submit]"), async () => {
try {
const { data } = await api("PUT", base + "/soa", { body: soaBody(form), ifMatch: etag });
dialog.close();
reportWarnings("SOA saved.", data);
await load();
} catch (err) {
handleError(err, { form, reload: () => { dialog.close(); return load(); } });
}
});
});
$("#soa-managed").addEventListener("click", async (event) => {
const soa = state.summary && state.summary.soa;
if (!soa) return;
await busy(event.target, async () => {
try {
const body = { ns: soa.ns, mbox: soa.mbox, ttl: soa.ttl, refresh: soa.refresh, retry: soa.retry, expire: soa.expire, minttl: soa.minttl, managed_serial: true };
await api("PUT", base + "/soa", { body, ifMatch: soa.etag });
toast("The zone now uses a managed serial.");
await load();
} catch (err) {
handleError(err, { reload: load });
}
});
});
}
function reportWarnings(message, data) {
const warnings = data && Array.isArray(data.warnings) ? data.warnings : [];
toast(message);
for (const warning of warnings) toast("Warning: " + warning.message, { kind: "warning" });
}
const recordForm = {
editing: null,
ttlTouched: false,
another: false,
pending: 0,
session: 0,
};
function fieldId(key) {
return "rec-f-" + key;
}
function readTypeValues(form) {
const values = {};
for (const control of form.querySelectorAll("#rec-fields [name]")) values[control.name] = control.value;
return values;
}
function buildTypeFields(type, values) {
const container = $("#rec-fields");
clear(container);
const specs = FIELD_SPECS[type] || [];
for (const spec of specs) {
const id = fieldId(spec.key);
let control;
const current = values[spec.key] === undefined || values[spec.key] === null ? "" : String(values[spec.key]);
if (spec.options) {
const choices = current !== "" && !spec.options.some(([value]) => value === current) ? [...spec.options, [current, current]] : spec.options;
control = h("select", { id, name: spec.key }, choices.map(([value, label]) => option(value, label, value === current)));
} else if (spec.multiline) {
control = h("textarea", { id, name: spec.key, rows: 3, autocomplete: "off", spellcheck: "false", placeholder: spec.placeholder, value: current });
} else {
control = h("input", {
id,
name: spec.key,
type: "text",
autocomplete: "off",
autocapitalize: "none",
spellcheck: "false",
inputmode: spec.numeric ? "numeric" : null,
placeholder: spec.placeholder,
value: current,
});
}
container.append(h("div", { class: "field" }, h("label", { for: id, text: spec.label }), control));
}
}
function updatePreview() {
const form = $("#record-form");
const result = previewName(form.elements.name.value, zoneName());
const hint = $("#rec-fqdn");
hint.textContent = result.error ? result.error : "Full name: " + result.fqdn;
if (!recordForm.ttlTouched && !recordForm.editing) applyRrsetTtl(result);
}
function applyRrsetTtl(result) {
const form = $("#record-form");
const type = form.elements.type.value;
let ttl = 3600;
if (!result.error) {
const match = state.records.find((record) => record.name === result.name && record.type === type && Number.isInteger(record.ttl) && record.ttl >= 0);
if (match) ttl = match.ttl;
}
form.elements.ttl.value = String(ttl);
}
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;
recordForm.ttlTouched = Boolean(record);
$("#record-dialog-title").textContent = record ? "Edit record" : "Add record";
$("#record-broken").hidden = !broken;
$("#record-raw").textContent = broken && record.raw !== null && record.raw !== undefined ? String(record.raw) : "";
const select = form.elements.type;
clear(select);
if (record && !known) select.append(option("", "Select a type", true));
for (const type of EDITABLE_TYPES) select.append(option(type, type, record ? record.type === type : type === "A"));
select.disabled = Boolean(record) && known;
form.elements.name.value = record ? displayName(record) : "";
const ttl = record && Number.isInteger(record.ttl) && record.ttl >= 0 ? record.ttl : 3600;
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"));
}
function recordBody(form) {
const type = form.elements.type.value;
const data = {};
for (const spec of FIELD_SPECS[type] || []) {
const value = form.elements[spec.key].value;
data[spec.key] = spec.numeric || spec.options ? parseNumber(value) : spec.hex ? value.replace(/[\s:]/g, "").toLowerCase() : spec.multiline || (type === "CAA" && spec.key === "value") ? value : value.trim();
}
return { name: form.elements.name.value.trim(), type, ttl: parseNumber(form.elements.ttl.value), data };
}
function setupRecordForm() {
const dialog = $("#record-dialog");
const form = $("#record-form");
$("#record-add").addEventListener("click", () => openRecord(null));
form.elements.name.addEventListener("input", updatePreview);
form.elements.ttl.addEventListener("input", () => {
recordForm.ttlTouched = true;
});
form.elements.type.addEventListener("change", () => {
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;
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();
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();
}
}
});
}
async function deleteRecord(record) {
const label = displayName(record) + " " + record.type + " " + presentValue(record);
const ok = await confirmDialog({ title: "Delete record", message: "Delete " + label + "?", confirm: "Delete" });
if (!ok) return;
try {
const { data } = await api("DELETE", base + "/records/" + record.id, { ifMatch: record.etag });
state.selected.delete(record.id);
reportWarnings("Record deleted.", data);
await load();
} catch (err) {
handleError(err, { reload: load });
}
}
async function bulkDelete() {
const items = state.records.filter((record) => state.selected.has(record.id) && record.type !== "SOA");
if (items.length === 0) return;
const ok = await confirmDialog({ title: "Delete records", message: "Delete " + plural(items.length, "selected record", "selected records") + "? Either all of them are deleted or none.", confirm: "Delete" });
if (!ok) return;
try {
const { data } = await api("POST", base + "/records/delete", { body: { records: items.map((record) => ({ id: record.id, etag: record.etag })) } });
state.selected.clear();
reportWarnings(plural(data && Number.isInteger(data.deleted) ? data.deleted : items.length, "record", "records") + " deleted.", data);
await load();
} catch (err) {
handleError(err, { reload: load });
}
}
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();
});
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();
});
$("#page-next").addEventListener("click", () => {
state.page += 1;
renderRecords();
});
$("#select-all").addEventListener("change", (event) => {
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);
}
renderRecords();
});
$("#bulk-delete").addEventListener("click", bulkDelete);
}
async function loadUsers() {
const list = $("#zone-users");
const status = $("#zone-users-status");
const pick = $("#zone-user-pick");
try {
const [delegated, users] = await Promise.all([api("GET", base + "/users"), api("GET", "/users")]);
const current = delegated.data.users || [];
const names = new Set(current.map((user) => user.username));
clear(list);
for (const user of current) {
list.append(h("li", null,
h("span", { class: "mono", text: user.username }),
" ",
h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Remove " + user.username + " from this zone", onclick: () => removeUser(user.username) }, icon("trash"), " Remove")));
}
status.textContent = current.length === 0 ? "The zone is not delegated to any user." : "";
const candidates = (users.data.users || []).filter((user) => user.role === "user" && !names.has(user.username));
clear(pick);
for (const user of candidates) pick.append(option(user.username, user.username, false));
$("#zone-user-add").disabled = candidates.length === 0;
pick.disabled = candidates.length === 0;
if (candidates.length === 0) pick.append(option("", "No user available", true));
} catch (err) {
status.textContent = "The users could not be loaded.";
handleError(err);
}
}
async function removeUser(username) {
const ok = await confirmDialog({ title: "Remove user", message: "Remove " + username + " from this zone?", confirm: "Remove" });
if (!ok) return;
try {
await api("DELETE", base + "/users/" + encodeURIComponent(username));
toast("Delegation removed.");
await loadUsers();
} catch (err) {
handleError(err, { reload: loadUsers });
}
}
function setupAdmin() {
$("#zone-user-form").addEventListener("submit", async (event) => {
event.preventDefault();
const username = $("#zone-user-pick").value;
if (!username) return;
await busy($("#zone-user-add"), async () => {
try {
await api("PUT", base + "/users/" + encodeURIComponent(username));
toast("Zone delegated to " + username + ".");
await loadUsers();
} catch (err) {
handleError(err);
}
});
});
const confirmInput = $("#zone-delete-confirm");
const deleteButton = $("#zone-delete");
confirmInput.addEventListener("input", () => {
deleteButton.disabled = stripDot(confirmInput.value.trim().toLowerCase()) !== stripDot(zoneName().toLowerCase());
});
$("#zone-delete-form").addEventListener("submit", async (event) => {
event.preventDefault();
if (deleteButton.disabled) return;
await busy(deleteButton, async () => {
try {
await api("DELETE", base, { body: { confirm: confirmInput.value.trim() } });
flash("Zone " + zoneName() + " deleted. The DNS server stops serving it after its next zone list reload, which happens every 10 minutes by default.");
location.assign("/");
} catch (err) {
handleError(err);
}
});
});
}
setupDialogs();
showFlash();
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();
if (isAdmin) setupAdmin();
load();