ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m48s
ci / test (pull_request) Successful in 12m42s
ci / build (pull_request) Canceled after 30s
ci / image (pull_request) Canceled after 0s
Regions get an optional location. Platform admins set it for platform regions and org admins for their own, by clicking the map on the regions page or entering the coordinates; PATCH /org/regions/:id and /admin/regions/:id set or remove it. The monitor form shows the located regions on a map from the self-hosted ZB-Server Maps: a click on a marker ticks or unticks the region, and the checkbox list stays the source of truth. MapLibre loads only on pages with a map, and the map stays hidden if the map server cannot be reached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
722 lines
30 KiB
JavaScript
722 lines
30 KiB
JavaScript
(() => {
|
|
const meta = document.querySelector('meta[name="csrf-token"]');
|
|
const api = axios.create({ baseURL: "/api/v1", withCredentials: true });
|
|
api.interceptors.request.use((cfg) => {
|
|
if (meta?.content) cfg.headers["X-CSRF-Token"] = meta.content;
|
|
return cfg;
|
|
});
|
|
window.api = api;
|
|
|
|
const message = (err) =>
|
|
err.response?.data?.message ?? document.body.dataset.msgNetwork;
|
|
|
|
const showError = (form, text) => {
|
|
const el = form.querySelector("[data-error]");
|
|
if (!el) return;
|
|
el.textContent = text;
|
|
el.classList.toggle("hidden", !text);
|
|
};
|
|
|
|
// Inputs inside a hidden [data-step] are skipped. Checkboxes become
|
|
// booleans, or arrays of values with [data-multi]; [data-list] inputs are
|
|
// split on commas, [data-number] parsed and empty [data-nullable] sent as null.
|
|
// [data-headers] textareas become objects from "Name: value" lines.
|
|
// Dotted names such as "config.keyword" build nested objects.
|
|
const serialize = (form) => {
|
|
const out = {};
|
|
// Numeric segments build arrays: "config.assertions.0.path".
|
|
const set = (name, value) => {
|
|
const path = name.split(".");
|
|
let obj = out;
|
|
path.slice(0, -1).forEach((key, i) => {
|
|
obj = obj[key] ??= /^\d+$/.test(path[i + 1]) ? [] : {};
|
|
});
|
|
obj[path.at(-1)] = value;
|
|
};
|
|
const get = (name) => name.split(".").reduce((o, k) => o?.[k], out);
|
|
for (const el of form.elements) {
|
|
if (!el.name || el.type === "fieldset" || el.closest("[data-step]")?.hidden) continue;
|
|
// :disabled also covers fields inside a disabled fieldset, such as
|
|
// the settings of other monitor types.
|
|
const disabled = el.matches(":disabled");
|
|
if (el.dataset.multi !== undefined) {
|
|
if (get(el.name) === undefined) set(el.name, []);
|
|
if (el.checked && !disabled) get(el.name).push(el.value);
|
|
continue;
|
|
}
|
|
if (disabled) continue;
|
|
// "<resource_type>:<id>" limits an assignment to one resource.
|
|
if (el.dataset.scope !== undefined) {
|
|
const [type, id] = el.value.split(":");
|
|
if (id) {
|
|
set("resource_type", type);
|
|
set("resource_id", id);
|
|
}
|
|
continue;
|
|
}
|
|
if (el.type === "checkbox") set(el.name, el.checked);
|
|
// [data-number][data-nullable] sends null when left empty.
|
|
else if (el.dataset.number !== undefined)
|
|
set(el.name, el.value === "" && el.dataset.nullable !== undefined ? null : Number(el.value));
|
|
else if (el.dataset.nullable !== undefined) set(el.name, el.value || null);
|
|
else if (el.dataset.headers !== undefined)
|
|
set(el.name, Object.fromEntries(
|
|
el.value.split("\n").map((l) => l.split(":")).filter((p) => p.length > 1 && p[0].trim())
|
|
.map(([k, ...v]) => [k.trim(), v.join(":").trim()])));
|
|
else if (el.dataset.list !== undefined)
|
|
set(el.name, el.value.split(",").map((v) => v.trim()).filter(Boolean));
|
|
else set(el.name, el.value);
|
|
}
|
|
// Forms with data-rows="name" send the checked [data-row] elements as an
|
|
// array of objects built from their [data-field] inputs.
|
|
if (form.dataset.rows) {
|
|
out[form.dataset.rows] = [...form.querySelectorAll("[data-row]")]
|
|
.filter((row) => row.querySelector('[data-field="include"]')?.checked)
|
|
.map((row) => {
|
|
const obj = {};
|
|
for (const f of row.querySelectorAll("[data-field]")) {
|
|
if (f.dataset.field !== "include") {
|
|
obj[f.dataset.field] = f.dataset.nullable !== undefined ? (f.value || null) : f.value;
|
|
}
|
|
}
|
|
return obj;
|
|
});
|
|
}
|
|
return out;
|
|
};
|
|
|
|
// fillInstall completes the install instructions of a new agent with its
|
|
// token and kind; the checkbox picks the self-updating image or not.
|
|
const fillInstall = (form, token) => {
|
|
const box = form.querySelector("[data-install]");
|
|
if (!box) return;
|
|
const kind = form.elements.kind?.value || "checker";
|
|
const auto = box.querySelector("[data-install-auto]");
|
|
const render = () => {
|
|
const channel = box.dataset.channel;
|
|
const values = {
|
|
token,
|
|
kind,
|
|
manual: auto.checked ? "" : " --manual-updates",
|
|
tag: auto.checked ? `${channel}-autoupdate` : channel,
|
|
};
|
|
for (const el of box.querySelectorAll("[data-install-fill]")) {
|
|
el.textContent = el.dataset.installFill.replace(/\{(\w+)\}/g, (m, k) => values[k] ?? m);
|
|
}
|
|
for (const el of box.querySelectorAll("[data-install-kind]")) {
|
|
el.hidden = el.dataset.installKind !== kind;
|
|
}
|
|
};
|
|
auto.onchange = render;
|
|
render();
|
|
};
|
|
|
|
document.addEventListener("submit", async (ev) => {
|
|
const form = ev.target.closest("form[data-api]");
|
|
if (!form) return;
|
|
ev.preventDefault();
|
|
if (form.dataset.created !== undefined) return;
|
|
if (form.dataset.confirm && !confirm(form.dataset.confirm)) return;
|
|
const button = form.querySelector("button[type=submit]");
|
|
const body = serialize(form);
|
|
const totpStep = form.querySelector('[data-step="totp"]');
|
|
const url = totpStep && !totpStep.hidden ? `${form.dataset.api}/totp` : form.dataset.api;
|
|
|
|
showError(form, "");
|
|
button && (button.disabled = true);
|
|
try {
|
|
const res = await api.request({ method: form.dataset.method || "post", url, data: body });
|
|
if (form.dataset.showCodes !== undefined && res.data?.recovery_codes) {
|
|
const out = form.querySelector("[data-recovery-output]");
|
|
const list = out.querySelector("[data-recovery-list]");
|
|
list.replaceChildren(
|
|
...res.data.recovery_codes.map((c) => Object.assign(document.createElement("li"), { textContent: c })),
|
|
);
|
|
for (const el of form.elements) el.disabled = true;
|
|
out.hidden = false;
|
|
return;
|
|
}
|
|
const shown = res.data?.url || res.data?.token || res.data?.signing_secret;
|
|
if (form.dataset.showLink !== undefined && shown) {
|
|
const out = form.querySelector("[data-link-output]");
|
|
const input = out.querySelector("[data-link]");
|
|
input.value = shown;
|
|
out.hidden = false;
|
|
input.select();
|
|
fillInstall(form, shown);
|
|
if (form.dataset.refreshTarget) {
|
|
// Keep the one-time secret visible while refreshing the channel list
|
|
// and group choices. A successful create must not be submitted twice.
|
|
form.dataset.created = "true";
|
|
const response = await fetch(location.href, { credentials: "same-origin" });
|
|
if (!response.ok) throw new Error("refresh failed");
|
|
const page = new DOMParser().parseFromString(await response.text(), "text/html");
|
|
const selector = form.dataset.refreshTarget;
|
|
const updated = page.querySelector(selector);
|
|
const current = document.querySelector(selector);
|
|
if (!updated || !current) throw new Error("refresh target missing");
|
|
current.replaceWith(updated);
|
|
}
|
|
return;
|
|
}
|
|
if (res.data?.status === "totp_required" && totpStep) {
|
|
form.querySelector('[data-step="password"]').hidden = true;
|
|
totpStep.hidden = false;
|
|
totpStep.querySelector("input")?.focus();
|
|
return;
|
|
}
|
|
let next = form.dataset.next || location.href;
|
|
if (form.dataset.nextFrom) next += res.data?.[form.dataset.nextFrom] ?? "";
|
|
// The server may name where to go, within this site.
|
|
const redirect = res.data?.redirect;
|
|
if (typeof redirect === "string" && redirect.startsWith("/") && !redirect.startsWith("//")) next = redirect;
|
|
location.assign(next);
|
|
} catch (err) {
|
|
showError(form, message(err));
|
|
} finally {
|
|
button && (button.disabled = form.dataset.created !== undefined);
|
|
}
|
|
});
|
|
|
|
// Saves the order of a list of monitors being arranged.
|
|
const saveOrder = async (list) => {
|
|
const ids = [...list.querySelectorAll(":scope > [data-sort-id]")].map((li) => li.dataset.sortId);
|
|
try {
|
|
await api.put(list.dataset.sortable, { monitor_ids: ids });
|
|
} catch (err) {
|
|
alert(message(err));
|
|
location.reload();
|
|
}
|
|
};
|
|
let dragged = null;
|
|
document.addEventListener("dragstart", (ev) => {
|
|
const item = ev.target.closest?.("[data-sortable] > [data-sort-id]");
|
|
if (!item) return;
|
|
dragged = item;
|
|
ev.dataTransfer.effectAllowed = "move";
|
|
item.style.opacity = "0.5";
|
|
});
|
|
document.addEventListener("dragover", (ev) => {
|
|
const over = ev.target.closest?.("[data-sortable] > [data-sort-id]");
|
|
if (!dragged || !over || over === dragged || over.parentElement !== dragged.parentElement) return;
|
|
ev.preventDefault();
|
|
const box = over.getBoundingClientRect();
|
|
if (ev.clientY < box.top + box.height / 2) over.before(dragged);
|
|
else over.after(dragged);
|
|
});
|
|
document.addEventListener("drop", (ev) => {
|
|
if (dragged) ev.preventDefault();
|
|
});
|
|
document.addEventListener("dragend", async () => {
|
|
if (!dragged) return;
|
|
const list = dragged.parentElement;
|
|
dragged.style.opacity = "";
|
|
dragged = null;
|
|
await saveOrder(list);
|
|
});
|
|
|
|
document.addEventListener("click", async (ev) => {
|
|
const navToggle = ev.target.closest("[data-nav-toggle]");
|
|
if (navToggle) {
|
|
const nav = document.getElementById(navToggle.dataset.navToggle);
|
|
const open = nav?.classList.toggle("hidden") === false;
|
|
navToggle.setAttribute("aria-expanded", String(open));
|
|
return;
|
|
}
|
|
// Moves a monitor up or down while arranging the monitor list.
|
|
const move = ev.target.closest("[data-sort-move]");
|
|
if (move) {
|
|
const item = move.closest("[data-sort-id]");
|
|
const other = move.dataset.sortMove === "up" ? item.previousElementSibling : item.nextElementSibling;
|
|
if (!other) return;
|
|
if (move.dataset.sortMove === "up") other.before(item);
|
|
else other.after(item);
|
|
move.focus();
|
|
await saveOrder(item.closest("[data-sortable]"));
|
|
return;
|
|
}
|
|
// Ticks or clears every checkbox named by data-check-all in its form,
|
|
// of the rows a filter leaves visible.
|
|
const checkAll = ev.target.closest("[data-check-all]");
|
|
if (checkAll) {
|
|
const on = checkAll.dataset.checkAll === "on";
|
|
checkAll.closest("form")?.querySelectorAll(checkAll.dataset.checkTarget).forEach((box) => {
|
|
if (box.closest("[data-row]")?.hasAttribute("data-filtered-out")) return;
|
|
box.checked = on;
|
|
if (on) addRowFields(box);
|
|
});
|
|
return;
|
|
}
|
|
const locale = ev.target.closest("[data-locale]");
|
|
if (locale) {
|
|
await api.post("/locale", { locale: locale.dataset.locale }).catch(() => {});
|
|
location.reload();
|
|
return;
|
|
}
|
|
const del = ev.target.closest("[data-delete]");
|
|
if (del) {
|
|
if (del.dataset.confirm && !confirm(del.dataset.confirm)) return;
|
|
try {
|
|
await api.delete(del.dataset.delete);
|
|
if (del.dataset.next) location.assign(del.dataset.next);
|
|
else location.reload();
|
|
} catch (err) {
|
|
alert(message(err));
|
|
}
|
|
return;
|
|
}
|
|
const post = ev.target.closest("[data-post]");
|
|
if (post) {
|
|
if (post.dataset.confirm && !confirm(post.dataset.confirm)) return;
|
|
post.disabled = true;
|
|
try {
|
|
await api.post(post.dataset.post);
|
|
alert(post.dataset.ok);
|
|
if (post.dataset.reload !== undefined) location.reload();
|
|
} catch (err) {
|
|
alert(message(err));
|
|
} finally {
|
|
post.disabled = false;
|
|
}
|
|
return;
|
|
}
|
|
if (ev.target.closest("[data-logout]")) {
|
|
await api.post("/auth/logout").catch(() => {});
|
|
location.assign("/login");
|
|
}
|
|
const quietAdd = ev.target.closest("[data-quiet-add]");
|
|
if (quietAdd) {
|
|
const box = quietAdd.closest("[data-quiet-hours]");
|
|
const list = box?.querySelector("[data-quiet-list]");
|
|
const tpl = box?.querySelector("template[data-quiet-template]");
|
|
if (list && tpl) {
|
|
const idx = list.querySelectorAll("[data-quiet-row]").length;
|
|
const frag = tpl.content.cloneNode(true);
|
|
for (const el of frag.querySelectorAll("[name]")) {
|
|
el.name = el.name.replace("__INDEX__", String(idx));
|
|
}
|
|
for (const el of frag.querySelectorAll("input[data-tz-default]")) {
|
|
if (!el.value) el.value = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
}
|
|
list.appendChild(frag);
|
|
}
|
|
return;
|
|
}
|
|
const quietRemove = ev.target.closest("[data-quiet-remove]");
|
|
if (quietRemove) {
|
|
const list = quietRemove.closest("[data-quiet-list]");
|
|
quietRemove.closest("[data-quiet-row]")?.remove();
|
|
if (list) {
|
|
[...list.querySelectorAll("[data-quiet-row]")].forEach((row, i) => {
|
|
for (const el of row.querySelectorAll("[name]")) {
|
|
el.name = el.name.replace(/^quiet_hours\.\d+\./, `quiet_hours.${i}.`);
|
|
}
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
if (ev.target.closest("[data-totp-start]")) {
|
|
const root = ev.target.closest("[data-totp-setup]");
|
|
try {
|
|
const { data } = await api.post("/me/totp/setup");
|
|
root.querySelector("[data-totp-qr]").src = data.qr;
|
|
root.querySelector("[data-totp-secret]").textContent = data.secret;
|
|
root.querySelector("[data-totp-panel]").hidden = false;
|
|
ev.target.hidden = true;
|
|
} catch (err) {
|
|
alert(message(err));
|
|
}
|
|
}
|
|
});
|
|
|
|
// A row of a long list may come without its fields until it is ticked;
|
|
// they are copied in from the form's template[data-row-fields].
|
|
function addRowFields(box) {
|
|
const row = box.closest("[data-row]");
|
|
const tpl = row?.closest("form")?.querySelector("template[data-row-fields]");
|
|
if (!tpl || row.querySelector("[data-row-extra]")) return;
|
|
row.append(tpl.content.cloneNode(true));
|
|
}
|
|
document.addEventListener("change", (ev) => {
|
|
if (ev.target.matches('[data-row] [data-field="include"]') && ev.target.checked) addRowFields(ev.target);
|
|
});
|
|
|
|
// Lists with data-page-size show that many of their rows at a time, of
|
|
// those a filter leaves; the [data-row-pager] naming the list turns the
|
|
// pages. The other rows stay in the DOM, so forms still send them.
|
|
// Selects with data-lazy-options hold their chosen option only; the full
|
|
// list comes from the form's row template once the row is shown or used.
|
|
const fillOptions = (sel) => {
|
|
const tpl = sel.closest("form")?.querySelector("template[data-row-fields]");
|
|
const full = tpl?.content.querySelector(`select[data-field="${sel.dataset.field}"]`);
|
|
if (!full) return;
|
|
const value = sel.value;
|
|
sel.replaceChildren(...[...full.options].map((o) => o.cloneNode(true)));
|
|
sel.value = value;
|
|
sel.removeAttribute("data-lazy-options");
|
|
};
|
|
document.addEventListener("focusin", (ev) => {
|
|
if (ev.target.matches?.("select[data-lazy-options]")) fillOptions(ev.target);
|
|
});
|
|
const showRowPage = (list, page) => {
|
|
const rows = [...list.querySelectorAll(":scope > [data-row]")];
|
|
const size = Number(list.dataset.pageSize) || rows.length || 1;
|
|
const shown = rows.filter((row) => !row.hasAttribute("data-filtered-out"));
|
|
const pages = Math.max(1, Math.ceil(shown.length / size));
|
|
page = Math.min(Math.max(0, page), pages - 1);
|
|
list.dataset.page = String(page);
|
|
for (const row of rows) row.hidden = true;
|
|
for (const row of shown.slice(page * size, (page + 1) * size)) {
|
|
row.hidden = false;
|
|
row.querySelectorAll("select[data-lazy-options]").forEach(fillOptions);
|
|
}
|
|
for (const nav of document.querySelectorAll(`[data-row-pager="#${list.id}"]`)) {
|
|
nav.hidden = pages < 2;
|
|
nav.querySelector('[data-row-page="prev"]').disabled = page === 0;
|
|
nav.querySelector('[data-row-page="next"]').disabled = page >= pages - 1;
|
|
const status = nav.querySelector("[data-row-page-status]");
|
|
if (status) {
|
|
const values = {
|
|
from: shown.length ? page * size + 1 : 0,
|
|
to: Math.min((page + 1) * size, shown.length),
|
|
total: shown.length,
|
|
};
|
|
status.textContent = status.dataset.template.replace(/\{(\w+)\}/g, (m, k) => values[k] ?? m);
|
|
}
|
|
}
|
|
};
|
|
for (const list of document.querySelectorAll("[data-page-size][id]")) showRowPage(list, 0);
|
|
document.addEventListener("click", (ev) => {
|
|
const btn = ev.target.closest("[data-row-page]");
|
|
if (!btn) return;
|
|
const list = document.querySelector(btn.closest("[data-row-pager]").dataset.rowPager);
|
|
showRowPage(list, Number(list.dataset.page || 0) + (btn.dataset.rowPage === "next" ? 1 : -1));
|
|
});
|
|
|
|
// [data-filter-rows] hides the rows of the list it names whose text, or
|
|
// that of their [data-filter-text], does not contain what is typed.
|
|
document.addEventListener("input", (ev) => {
|
|
const input = ev.target.closest("[data-filter-rows]");
|
|
if (!input) return;
|
|
const needle = input.value.trim().toLowerCase();
|
|
const list = document.querySelector(input.dataset.filterRows);
|
|
for (const row of list.querySelectorAll(":scope > [data-row]")) {
|
|
const text = (row.querySelector("[data-filter-text]") ?? row).textContent;
|
|
const out = needle !== "" && !text.toLowerCase().includes(needle);
|
|
row.toggleAttribute("data-filtered-out", out);
|
|
row.hidden = out;
|
|
}
|
|
if (list.dataset.pageSize) showRowPage(list, 0);
|
|
});
|
|
|
|
// Only the settings of the selected check type are shown and submitted.
|
|
document.addEventListener("change", (ev) => {
|
|
const sel = ev.target.closest("[data-type-select]");
|
|
if (!sel) return;
|
|
for (const fs of sel.form.querySelectorAll("fieldset[data-type]")) {
|
|
const active = fs.dataset.type === sel.value;
|
|
fs.hidden = !active;
|
|
fs.disabled = !active;
|
|
}
|
|
// [data-hide-for] holds fields a type does without, e.g. heartbeats
|
|
// have neither target nor regions.
|
|
for (const el of sel.form.querySelectorAll("[data-hide-for]")) {
|
|
const hide = el.dataset.hideFor.split(" ").includes(sel.value);
|
|
el.hidden = hide;
|
|
if (el.tagName === "FIELDSET") el.disabled = hide;
|
|
for (const input of el.querySelectorAll("input[required], input[data-required]")) {
|
|
input.required = !hide;
|
|
input.dataset.required = "";
|
|
}
|
|
}
|
|
});
|
|
|
|
// Forms with [data-autosave] are sent as soon as a field changes, such
|
|
// as a single switch in a list.
|
|
document.addEventListener("change", (ev) => {
|
|
const form = ev.target.closest("form[data-autosave]");
|
|
if (form) form.requestSubmit();
|
|
});
|
|
|
|
document.addEventListener("change", async (ev) => {
|
|
const sel = ev.target.closest("[data-switch-org]");
|
|
if (!sel) return;
|
|
await api.post("/me/org", { org_id: sel.value });
|
|
location.reload();
|
|
});
|
|
})();
|
|
|
|
// Time zone fields start with the browser's zone.
|
|
for (const el of document.querySelectorAll("input[data-tz-default]")) {
|
|
if (!el.value) el.value = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
}
|
|
|
|
// Markdown editors: toolbar, shortcuts, list continuation, character count
|
|
// and a preview rendered by the server, so it matches what is published.
|
|
(() => {
|
|
// insertText keeps the browser's undo history, setRangeText is the
|
|
// fallback where it is unsupported.
|
|
const replace = (ta, start, end, text, selStart, selEnd) => {
|
|
ta.focus();
|
|
ta.setSelectionRange(start, end);
|
|
if (!document.execCommand("insertText", false, text)) {
|
|
ta.setRangeText(text, start, end, "end");
|
|
}
|
|
ta.setSelectionRange(start + selStart, start + selEnd);
|
|
ta.dispatchEvent(new Event("input", { bubbles: true }));
|
|
};
|
|
|
|
const wrap = (ta, mark, placeholder) => {
|
|
const { selectionStart: s, selectionEnd: e, value } = ta;
|
|
const sel = value.slice(s, e);
|
|
if (value.slice(s - mark.length, s) === mark && value.slice(e, e + mark.length) === mark) {
|
|
replace(ta, s - mark.length, e + mark.length, sel, 0, sel.length);
|
|
return;
|
|
}
|
|
const inner = sel || placeholder;
|
|
replace(ta, s, e, mark + inner + mark, mark.length, mark.length + inner.length);
|
|
};
|
|
|
|
// Prefixes every selected line, or removes the prefix when all have it.
|
|
const prefixLines = (ta, prefixFor, pattern) => {
|
|
const { selectionStart: s, selectionEnd: e, value } = ta;
|
|
const start = value.lastIndexOf("\n", s - 1) + 1;
|
|
const nl = value.indexOf("\n", e);
|
|
const end = nl === -1 ? value.length : nl;
|
|
const lines = value.slice(start, end).split("\n");
|
|
const all = lines.every((l) => pattern.test(l));
|
|
const out = lines.map((l, i) => (all ? l.replace(pattern, "") : prefixFor(i) + l)).join("\n");
|
|
replace(ta, start, end, out, 0, out.length);
|
|
};
|
|
|
|
const block = (ta, text, selFrom, selTo) => {
|
|
const { selectionStart: s, selectionEnd: e, value } = ta;
|
|
const before = s > 0 && value[s - 1] !== "\n" ? "\n\n" : "";
|
|
replace(ta, s, e, before + text, before.length + selFrom, before.length + selTo);
|
|
};
|
|
|
|
const actions = {
|
|
bold: (ta) => wrap(ta, "**", "text"),
|
|
italic: (ta) => wrap(ta, "_", "text"),
|
|
strike: (ta) => wrap(ta, "~~", "text"),
|
|
code: (ta) => wrap(ta, "`", "code"),
|
|
heading: (ta) => prefixLines(ta, () => "## ", /^#{1,6} /),
|
|
ul: (ta) => prefixLines(ta, () => "- ", /^[-*+] /),
|
|
ol: (ta) => prefixLines(ta, (i) => `${i + 1}. `, /^\d+\. /),
|
|
quote: (ta) => prefixLines(ta, () => "> ", /^> ?/),
|
|
link: (ta) => {
|
|
const { selectionStart: s, selectionEnd: e, value } = ta;
|
|
const text = value.slice(s, e) || "text";
|
|
const url = "https://";
|
|
replace(ta, s, e, `[${text}](${url})`, text.length + 3, text.length + 3 + url.length);
|
|
},
|
|
codeblock: (ta) => {
|
|
const sel = ta.value.slice(ta.selectionStart, ta.selectionEnd) || "code";
|
|
block(ta, "```\n" + sel + "\n```\n", 4, 4 + sel.length);
|
|
},
|
|
table: (ta) => block(ta, "| Column | Column |\n| --- | --- |\n| Cell | Cell |\n", 2, 8),
|
|
hr: (ta) => block(ta, "---\n", 4, 4),
|
|
};
|
|
const shortcuts = { b: "bold", i: "italic", k: "link" };
|
|
|
|
// Enter on a list item continues the list; on an empty item it ends it.
|
|
const continueList = (ta, ev) => {
|
|
const { selectionStart: s, selectionEnd: e, value } = ta;
|
|
if (s !== e) return;
|
|
const start = value.lastIndexOf("\n", s - 1) + 1;
|
|
const line = value.slice(start, s);
|
|
const m = line.match(/^(\s*)([-*+]|(\d+)\.|>)( +)(.*)$/);
|
|
if (!m || value.slice(s, value.indexOf("\n", s) === -1 ? value.length : value.indexOf("\n", s)).trim()) return;
|
|
ev.preventDefault();
|
|
if (!m[5].trim()) {
|
|
replace(ta, start, s, "", 0, 0);
|
|
return;
|
|
}
|
|
const marker = m[3] ? `${Number(m[3]) + 1}.` : m[2];
|
|
const next = "\n" + m[1] + marker + m[4];
|
|
replace(ta, s, s, next, next.length, next.length);
|
|
};
|
|
|
|
for (const ed of document.querySelectorAll("[data-md-editor]")) {
|
|
const ta = ed.querySelector("textarea");
|
|
const preview = ed.querySelector("[data-md-preview]");
|
|
const count = ed.querySelector("[data-md-count]");
|
|
const available = new Set([...ed.querySelectorAll("[data-md-action]")].map((b) => b.dataset.mdAction));
|
|
|
|
const updateCount = () => {
|
|
count.textContent = `${ta.value.length.toLocaleString()} / ${Number(ta.maxLength).toLocaleString()}`;
|
|
};
|
|
updateCount();
|
|
ta.addEventListener("input", updateCount);
|
|
|
|
ed.querySelector("[data-md-toolbar]").addEventListener("click", (ev) => {
|
|
const b = ev.target.closest("[data-md-action]");
|
|
if (b && !ta.hidden) actions[b.dataset.mdAction]?.(ta);
|
|
});
|
|
ta.addEventListener("keydown", (ev) => {
|
|
if ((ev.ctrlKey || ev.metaKey) && !ev.altKey && shortcuts[ev.key.toLowerCase()]) {
|
|
const name = shortcuts[ev.key.toLowerCase()];
|
|
if (!available.has(name)) return;
|
|
ev.preventDefault();
|
|
actions[name](ta);
|
|
} else if (ev.key === "Enter" && !ev.shiftKey && !ev.isComposing) {
|
|
continueList(ta, ev);
|
|
}
|
|
});
|
|
|
|
const show = async (tab) => {
|
|
for (const t of ed.querySelectorAll("[data-md-tab]")) t.setAttribute("aria-selected", String(t.dataset.mdTab === tab));
|
|
const previewing = tab === "preview";
|
|
ta.hidden = previewing;
|
|
preview.hidden = !previewing;
|
|
for (const b of ed.querySelectorAll("[data-md-action]")) b.disabled = previewing;
|
|
if (!previewing) {
|
|
ta.focus();
|
|
return;
|
|
}
|
|
if (!ta.value.trim()) {
|
|
preview.textContent = preview.dataset.empty;
|
|
return;
|
|
}
|
|
try {
|
|
const res = await window.api.post("/markdown/preview", { markdown: ta.value });
|
|
// The server renders without raw HTML or unsafe links.
|
|
preview.innerHTML = res.data.html;
|
|
} catch (err) {
|
|
preview.textContent = err.response?.data?.message ?? document.body.dataset.msgNetwork;
|
|
}
|
|
};
|
|
for (const t of ed.querySelectorAll("[data-md-tab]")) t.addEventListener("click", () => show(t.dataset.mdTab));
|
|
}
|
|
|
|
// Region maps show the [data-lat][data-lon] elements inside the element
|
|
// [data-region-items] selects, on the map server's tiles. MapLibre loads
|
|
// only on pages with a map, and the map stays hidden when it cannot.
|
|
let maplibre;
|
|
const loadMaplibre = (server) =>
|
|
(maplibre ??= window.maplibregl
|
|
? Promise.resolve(window.maplibregl)
|
|
: new Promise((resolve, reject) => {
|
|
const css = Object.assign(document.createElement("link"), { rel: "stylesheet", href: `${server}/vendor/maplibre-gl.css` });
|
|
const js = Object.assign(document.createElement("script"), { src: `${server}/vendor/maplibre-gl.js` });
|
|
js.onload = () => (window.maplibregl ? resolve(window.maplibregl) : reject(new Error("no MapLibre")));
|
|
js.onerror = reject;
|
|
document.head.append(css, js);
|
|
}));
|
|
const darkScheme = window.matchMedia?.("(prefers-color-scheme: dark)");
|
|
const mapStyle = (server) => `${server}/style-${darkScheme?.matches ? "dark" : "light"}.json`;
|
|
|
|
// A click on the map fills the coordinates of the location form last
|
|
// opened or focused, else the one marked [data-location-default].
|
|
let locationTarget = document.querySelector("[data-location-default]");
|
|
document.addEventListener("focusin", (ev) => {
|
|
const form = ev.target.closest?.("[data-location-form]");
|
|
if (form) locationTarget = form;
|
|
});
|
|
document.addEventListener("click", (ev) => {
|
|
const toggle = ev.target.closest("[data-location-toggle]");
|
|
if (toggle) {
|
|
const row = document.getElementById(toggle.dataset.locationToggle);
|
|
row.hidden = !row.hidden;
|
|
const form = row.querySelector("[data-location-form]");
|
|
if (!row.hidden) {
|
|
locationTarget = form;
|
|
row.querySelector("[data-location-field]")?.focus();
|
|
} else if (locationTarget === form) {
|
|
locationTarget = document.querySelector("[data-location-default]");
|
|
}
|
|
}
|
|
const clear = ev.target.closest("[data-location-clear]");
|
|
if (clear) {
|
|
const form = clear.closest("form");
|
|
for (const f of form.querySelectorAll("[data-location-field]")) f.value = "";
|
|
form.requestSubmit();
|
|
}
|
|
});
|
|
|
|
const initRegionMap = async (box) => {
|
|
const server = box.dataset.mapServer;
|
|
let gl;
|
|
try {
|
|
gl = await loadMaplibre(server);
|
|
} catch {
|
|
return;
|
|
}
|
|
const items = [...document.querySelectorAll(`${box.dataset.regionItems} [data-lat][data-lon]`)];
|
|
const lngLat = (item) => [Number(item.dataset.lon), Number(item.dataset.lat)];
|
|
box.hidden = false;
|
|
let map;
|
|
try {
|
|
map = new gl.Map({ container: box, style: mapStyle(server), center: [10.45, 51.17], zoom: 3 });
|
|
} catch {
|
|
box.hidden = true;
|
|
return;
|
|
}
|
|
let styled = false;
|
|
map.on("styledata", () => (styled = true));
|
|
map.on("error", () => {
|
|
if (!styled) box.hidden = true;
|
|
});
|
|
map.addControl(new gl.NavigationControl({ showCompass: false }), "top-right");
|
|
darkScheme?.addEventListener("change", () => map.setStyle(mapStyle(server)));
|
|
|
|
// The map may start hidden, as with the regions of passive monitor
|
|
// types, so it fits the markers once it has a size.
|
|
let fitted = false;
|
|
const fit = () => {
|
|
map.resize();
|
|
if (fitted || !box.clientWidth) return;
|
|
fitted = true;
|
|
const points = items.map(lngLat);
|
|
if (points.length > 1) {
|
|
const bounds = points.slice(1).reduce((b, p) => b.extend(p), new gl.LngLatBounds(points[0], points[0]));
|
|
map.fitBounds(bounds, { padding: 40, maxZoom: 6, duration: 0 });
|
|
} else if (points.length === 1) {
|
|
map.jumpTo({ center: points[0], zoom: 5 });
|
|
}
|
|
};
|
|
new ResizeObserver(fit).observe(box);
|
|
fit();
|
|
|
|
const selecting = box.dataset.regionMap === "select";
|
|
for (const item of items) {
|
|
const el = Object.assign(document.createElement("button"), { type: "button", className: "region-marker", title: item.dataset.name });
|
|
el.setAttribute("aria-label", item.dataset.name);
|
|
el.dataset.live = item.dataset.live;
|
|
new gl.Marker({ element: el }).setLngLat(lngLat(item)).addTo(map);
|
|
if (selecting) {
|
|
// The checkbox stays the source of truth; its change event keeps
|
|
// the form's own behaviour.
|
|
const paint = () => el.classList.toggle("is-checked", item.checked);
|
|
paint();
|
|
item.addEventListener("change", paint);
|
|
el.addEventListener("click", (ev) => {
|
|
ev.stopPropagation();
|
|
if (!item.matches(":disabled")) item.click();
|
|
});
|
|
} else {
|
|
el.classList.add("is-checked");
|
|
el.addEventListener("click", (ev) => {
|
|
ev.stopPropagation();
|
|
item.querySelector("[data-location-toggle]")?.click();
|
|
});
|
|
}
|
|
}
|
|
if (selecting) return;
|
|
let pick;
|
|
map.on("click", (ev) => {
|
|
if (!locationTarget) return;
|
|
const at = ev.lngLat.wrap ? ev.lngLat.wrap() : ev.lngLat;
|
|
const round = (v) => String(Math.round(v * 10000) / 10000);
|
|
locationTarget.querySelector('[data-location-field="latitude"]').value = round(at.lat);
|
|
locationTarget.querySelector('[data-location-field="longitude"]').value = round(at.lng);
|
|
const point = [at.lng, at.lat];
|
|
pick ??= new gl.Marker({ element: Object.assign(document.createElement("div"), { className: "region-marker is-pick" }) })
|
|
.setLngLat(point)
|
|
.addTo(map);
|
|
pick.setLngLat(point);
|
|
});
|
|
};
|
|
for (const box of document.querySelectorAll("[data-region-map]")) initRegionMap(box);
|
|
})();
|