v0.43.0
This commit is contained in:
1 parent
51631810e1
commit
e6176cfce3
28 files changed
+959
-506
No files matched your search
+146
-38
@@ -426,12 +426,63 @@ function openLocationHelp(topic = "locations") {
|
||||
}
|
||||
dialog.showModal();
|
||||
}
|
||||
// Error fallback = target internal location + the upstream statuses it handles.
|
||||
// The status chips write the legacy comma-separated "<prefix>-statuses" field,
|
||||
// so readers, JSON drawers and saved configuration keep their exact format.
|
||||
const ERROR_FALLBACK_STATUSES = [403, 404, 500, 502, 503, 504];
|
||||
let errorFallbackListId = 0;
|
||||
const internalLocationIds = () => [...form.querySelectorAll('.vh-location [name="location-internal"]')].filter(box => box.checked)
|
||||
.map(box => read("location-id", box.closest(".vh-location"))?.value.trim()).filter(Boolean);
|
||||
function errorFallbackFields(parent, prefix, value, keys) {
|
||||
const target = field(parent, `${prefix}-target`, keys.target, value?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
|
||||
target.placeholder = t("errorFallbackTargetPlaceholder"); target.autocomplete = "off";
|
||||
const list = el("datalist"); list.id = `vh-error-fallback-targets-${++errorFallbackListId}`; target.setAttribute("list", list.id); target.closest("label").append(list);
|
||||
const fillTargets = () => list.replaceChildren(...internalLocationIds().map(id => { const option = el("option"); option.value = id; return option; }));
|
||||
target.addEventListener("focus", fillTargets);
|
||||
const box = el("div", undefined, "vh-field vh-error-fallback-statuses"), caption = text("span", keys.statuses);
|
||||
const hidden = document.createElement("input"); hidden.type = "hidden"; hidden.name = `${prefix}-statuses`;
|
||||
const chips = el("div", undefined, "vh-status-chips"); chips.setAttribute("role", "group"); chips.setAttribute("aria-label", t(keys.statuses));
|
||||
const initial = [...new Set((value?.statuses?.length ? value.statuses : [404]).map(Number))];
|
||||
const choices = [...ERROR_FALLBACK_STATUSES, ...initial.filter(code => !ERROR_FALLBACK_STATUSES.includes(code))];
|
||||
const boxes = choices.map(code => {
|
||||
const label = el("label", undefined, "vh-status-chip"), input = document.createElement("input");
|
||||
input.type = "checkbox"; input.value = String(code); input.checked = initial.includes(code);
|
||||
label.append(input, el("span", String(code))); chips.append(label); return input;
|
||||
});
|
||||
const write = () => { hidden.value = boxes.filter(input => input.checked).map(input => input.value).join(", "); };
|
||||
const sync = () => { const off = !target.value.trim(); box.classList.toggle("is-inactive", off); for (const input of boxes) input.disabled = off; };
|
||||
chips.addEventListener("change", event => {
|
||||
// At least one status stays selected; an empty list would silently mean 404.
|
||||
if (!boxes.some(input => input.checked)) event.target.checked = true;
|
||||
write(); hidden.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
});
|
||||
target.addEventListener("input", sync);
|
||||
box.append(caption, chips, hidden); parent.append(box); write(); sync();
|
||||
return { target, statuses: hidden };
|
||||
}
|
||||
const LOCATION_GROUP = "__group__";
|
||||
function locationsEditor(parent, values, onChange = changed) {
|
||||
const toolbar = el("div", undefined, "vh-wide location-toolbar"), rows = el("div", undefined, "vh-wide vh-locations");
|
||||
const addTop = button("locationAdd", () => { add(); sync(); }, "primary");
|
||||
const addHostRule = button("rtAddHostRule", () => { add({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }, true); sync(); });
|
||||
toolbar.append(addTop, addHostRule, button("documentation", () => openLocationHelp("locations")));
|
||||
// "Add location" opens starting points; each one only pre-fills ordinary fields.
|
||||
const addMenu = el("div", undefined, "location-add-menu"), templates = el("div", undefined, "location-templates"); templates.hidden = true;
|
||||
const showTemplates = open => { templates.hidden = !open; addTop.setAttribute("aria-expanded", String(open)); };
|
||||
const addTop = button("locationAdd", () => showTemplates(templates.hidden), "primary"); addTop.setAttribute("aria-haspopup", "true"); addTop.setAttribute("aria-expanded", "false");
|
||||
const template = (key, helpKey, make, openConditions = false) => {
|
||||
const choice = el("button", undefined, "location-template"); choice.type = "button"; choice.append(text("b", key), text("span", helpKey, "fine"));
|
||||
choice.addEventListener("click", () => { showTemplates(false); add(make(), openConditions); sync(); rows.lastElementChild?.scrollIntoView({ block: "nearest" }); rows.lastElementChild?.querySelector('[name="location-id"]')?.focus(); });
|
||||
templates.append(choice);
|
||||
};
|
||||
template("locationTplProxy", "locationTplProxyHelp", () => ({ id: nextId("api"), path_prefix: "/api/", rewrite: { mode: "strip_prefix" } }));
|
||||
template("locationTplWeb", "locationTplWebHelp", () => ({ id: nextId("files"), path_prefix: "/static/", source: { type: "web_server", web_service_id: "" } }));
|
||||
template("locationTplRedirect", "locationTplRedirectHelp", () => ({ id: nextId("redirect"), path_prefix: "/old/", redirect: { status: 301, target: "", preserve_query: true } }));
|
||||
template("locationTplReturn", "locationTplReturnHelp", () => ({ id: nextId("health"), match_type: "exact", path_prefix: "/healthz", response: { status: 200, content_type: "text/plain; charset=utf-8", body: "ok" } }));
|
||||
template("locationTplInternal", "locationTplInternalHelp", () => ({ id: nextId("error"), internal: true }));
|
||||
template("rtAddHostRule", "locationTplHostHelp", () => ({ id: nextId("host-rule"), match_type: "any", conditions: [{ source: "header", name: "", operator: "equals", values: [] }] }), true);
|
||||
template("locationTplBlank", "locationTplBlankHelp", () => ({}));
|
||||
addMenu.addEventListener("keydown", event => { if (event.key === "Escape" && !templates.hidden) { event.preventDefault(); event.stopPropagation(); showTemplates(false); addTop.focus(); } });
|
||||
addMenu.addEventListener("focusout", event => { if (!addMenu.contains(event.relatedTarget)) showTemplates(false); });
|
||||
addMenu.append(addTop, templates);
|
||||
toolbar.append(addMenu, button("documentation", () => openLocationHelp("locations")));
|
||||
parent.append(toolbar); note(parent, "locationHelp"); note(parent, "rtOrderHelp");
|
||||
const tester = routingTester(parent, () => readRows());
|
||||
parent.append(rows); let reloading = false;
|
||||
@@ -464,32 +515,64 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
};
|
||||
});
|
||||
}
|
||||
function sync() { if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); onChange(); } catch { } tester?.run(); }
|
||||
function renumber() { [...rows.children].forEach((row, index) => { if (row._order) row._order.textContent = String(index + 1); }); }
|
||||
function sync() { renumber(); if (reloading) return; try { read("paths").value = JSON.stringify(readRows(), null, 2); onChange(); } catch { } tester?.run(); }
|
||||
function memberOptions(select, chosen = select.value) { const base = text("option", "locationPool"); base.value = ""; const groupOption = text("option", "locationBackendGroup"); groupOption.value = LOCATION_GROUP; select.replaceChildren(base, groupOption, ...[...form.querySelectorAll(".vh-member")].map(m => { const id = str("member-id", m), o = el("option", `${id} / ${str("member-url", m)}`); o.value = id; return o; })); if (chosen && !Array.from(select.options).some(o => o.value === chosen)) { const o = el("option", `${chosen} / ${t("locationMissing")}`); o.value = chosen; select.append(o); } select.value = chosen; }
|
||||
function add(value = {}, openConditions = false) {
|
||||
function add(value = {}, openConditions = false, open = true) {
|
||||
if (rows.children.length >= 64) { toast(t("locationLimit"), true); return; }
|
||||
const row = el("details", undefined, "vh-location"); row.open = true;
|
||||
const row = el("details", undefined, "vh-location"); row.open = open;
|
||||
const summary = el("summary", undefined, "location-summary"), body = el("div", undefined, "vh-grid location-body"); row.append(summary, body);
|
||||
// Collapsed row = one line of the routing table; expanded = When / What / Options.
|
||||
const sumOrder = el("span", String(rows.children.length + 1), "loc-order"), sumState = el("span", undefined, "loc-state"), sumId = el("span", "", "loc-id");
|
||||
const sumMatch = el("span", "", "loc-match"), sumPath = el("span", "", "loc-path"), sumAction = el("span", "", "loc-action"), sumChips = el("span", undefined, "loc-chips");
|
||||
sumState.setAttribute("role", "img"); summary.append(sumOrder, sumState, sumId, sumMatch, sumPath, sumAction, sumChips); row._order = sumOrder;
|
||||
const headline = el("p", "", "vh-wide location-headline"); body.append(headline);
|
||||
const card = (cls, number, key) => {
|
||||
const box = el("section", undefined, `location-card ${cls}`), head = el("h4", undefined, "location-card-title"), grid = el("div", undefined, "vh-grid location-card-grid");
|
||||
head.append(el("span", number, "location-step"), text("span", key)); box.append(head, grid); return [box, grid];
|
||||
};
|
||||
const [whenCard, whenGrid] = card("location-when", "1", "locationStepWhen"), [whatCard, whatGrid] = card("location-what", "2", "locationStepWhat");
|
||||
const cards = el("div", undefined, "vh-wide location-cards"); cards.append(whenCard, whatCard); body.append(cards);
|
||||
const options = el("section", undefined, "vh-wide location-options"), optionsHead = el("div", undefined, "location-options-head"), tabList = el("div", undefined, "location-tabs"), panels = el("div", undefined, "location-tab-panels");
|
||||
const optionsTitle = el("h4", undefined, "location-card-title"); optionsTitle.append(el("span", "3", "location-step"), text("span", "locationStepOptions"));
|
||||
tabList.setAttribute("role", "tablist"); optionsHead.append(optionsTitle, tabList); options.append(optionsHead, panels); body.append(options);
|
||||
const tabs = new Map(); let activeTab = "access";
|
||||
const optionTab = (name, key) => {
|
||||
const tab = el("button", undefined, "location-tab"), state = el("small", "", "location-tab-state"), panel = el("div", undefined, "vh-grid location-tab-panel");
|
||||
tab.type = "button"; tab.setAttribute("role", "tab"); tab.append(text("span", key), state); panel.setAttribute("role", "tabpanel"); panel.hidden = true;
|
||||
tab.addEventListener("click", () => selectTab(name)); tabList.append(tab); panels.append(panel); tabs.set(name, { tab, state, panel }); return panel;
|
||||
};
|
||||
const selectTab = name => {
|
||||
const available = item => !item.tab.hidden;
|
||||
let target = tabs.get(name); if (!target || !available(target)) target = [...tabs.values()].find(available);
|
||||
for (const [key, item] of tabs) { const on = item === target; if (on) activeTab = key; item.tab.setAttribute("aria-selected", String(on)); item.tab.classList.toggle("active", on); item.panel.hidden = !on; }
|
||||
};
|
||||
const setTabAvailable = (name, available) => { const item = tabs.get(name); item.tab.hidden = !available; if (!available && activeTab === name) selectTab("access"); else if (activeTab === name) selectTab(name); };
|
||||
const accessPanel = optionTab("access", "locationTabAccess"), headersPanel = optionTab("headers", "locationTabHeaders"), cachePanel = optionTab("cache", "locationTabCache");
|
||||
const errorsPanel = optionTab("errors", "locationTabErrors"), backendPanel = optionTab("backend", "locationBalancing"), policyPanel = optionTab("policy", "policyTitle");
|
||||
row.addEventListener("invalid", event => {
|
||||
const panel = event.target.closest?.(".location-tab-panel"), entry = panel && [...tabs].find(([, item]) => item.panel === panel);
|
||||
if (entry) selectTab(entry[0]); row.open = true;
|
||||
}, true);
|
||||
const used = new Set([...rows.children].map(r => str("location-id", r))); let suffix = 1; while (used.has(`location-${suffix}`)) suffix++;
|
||||
field(body, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 });
|
||||
const match = field(body, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] });
|
||||
const path = field(body, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/";
|
||||
const internal = field(body, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true });
|
||||
field(whenGrid, "location-id", "locationId", value.id || `location-${suffix}`, "text", { required: true, pattern: "[A-Za-z0-9_\\-]{1,64}", maxLength: 64 });
|
||||
const match = field(whenGrid, "location-match", "locationMatchType", value.match_type || "prefix", "select", { values: [["prefix", "locationMatchPrefix"], ["prefix_priority", "locationMatchPriority"], ["exact", "locationMatchExact"], ["regex", "locationMatchRegex"], ["regex_insensitive", "locationMatchRegexI"], ["any", "locationMatchAny"]] });
|
||||
const path = field(whenGrid, "location-path", "locationPathPattern", value.path_prefix || "/", "text", { required: true, maxLength: 1024 }); path.placeholder = "/api or ^/api/v[0-9]+/";
|
||||
const internal = field(whenGrid, "location-internal", "locationInternal", value.internal === true, "checkbox", { switch: true });
|
||||
const initialAction = value.response ? "return" : value.redirect ? "redirect" : value.source?.type === "web_server" ? "web_server" : "proxy";
|
||||
const action = field(body, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] });
|
||||
const action = field(whatGrid, "location-action", "locationAction", initialAction, "select", { values: [["proxy", "locationProxyAction"], ["web_server", "locationWebServerAction"], ["redirect", "locationRedirectAction"], ["return", "locationReturnAction"]] });
|
||||
const initialTarget = value.backend_ids?.length ? LOCATION_GROUP : value.backend_id || "";
|
||||
const backend = field(body, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget);
|
||||
const webService = field(body, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || "");
|
||||
field(body, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true });
|
||||
const cache = field(body, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] });
|
||||
const backend = field(whatGrid, "location-backend", "locationTarget", initialTarget, "select"); memberOptions(backend, initialTarget);
|
||||
const webService = field(whatGrid, "location-web-service", "webService", value.source?.web_service_id || "", "select"); fillWebServices(webService, value.source?.web_service_id || "");
|
||||
field(whatGrid, "location-enabled", "enabled", value.enabled !== false, "checkbox", { switch: true });
|
||||
const cache = field(cachePanel, "location-cache", "cacheEnabled", value.cache === true ? "on" : value.cache === false ? "off" : "", "select", { values: [["", "inherit"], ["on", "enabled"], ["off", "notEnabled"]] });
|
||||
|
||||
const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); body.append(conditionBox);
|
||||
const conditionBox = el("details", undefined, "vh-wide location-section location-conditions"), conditionBody = el("div", undefined, "vh-grid"); conditionBox.append(text("summary", "rtConditions"), conditionBody); whenGrid.append(conditionBox);
|
||||
conditionBox.open = openConditions || Boolean(value.conditions?.length);
|
||||
note(conditionBody, "rtConditionsHelp");
|
||||
const conditions = conditionsEditor(conditionBody, value.conditions || [], () => { syncUi(); sync(); }); row.readConditions = conditions.read;
|
||||
const conditionCacheNote = text("p", "rtNotCachedHelp", "fine vh-wide"); conditionBody.append(conditionCacheNote);
|
||||
const balancing = el("details", undefined, "vh-wide location-section location-balancing"), balancingBody = el("div", undefined, "vh-grid"); balancing.append(text("summary", "locationBalancing"), balancingBody); body.append(balancing);
|
||||
balancing.open = Boolean(value.backend_ids?.length || value.load_balancing);
|
||||
const balancingBody = backendPanel; balancingBody.classList.add("location-balancing");
|
||||
const groupBox = el("div", undefined, "vh-wide location-group"); groupBox.append(text("span", "locationGroupMembers", "location-group-title"));
|
||||
const groupList = el("div", undefined, "location-group-list"); groupBox.append(groupList, text("p", "locationGroupHelp", "fine")); balancingBody.append(groupBox);
|
||||
const groupSelected = new Set(value.backend_ids || []);
|
||||
@@ -503,7 +586,7 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
}));
|
||||
};
|
||||
row.groupIds = () => { const ids = balancingMembers().map(m => m.id).filter(id => groupSelected.has(id)); if (!ids.length) throw new Error(t("locationGroupEmpty").replace("{location}", str("location-id", row))); return ids; };
|
||||
backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) balancing.open = true; });
|
||||
backend.addEventListener("change", () => { if (backend.value === LOCATION_GROUP) selectTab("backend"); });
|
||||
const ownBalancing = field(balancingBody, "location-lb-custom", "lbLocationOwn", Boolean(value.load_balancing), "checkbox", { switch: true });
|
||||
const balancingSlot = el("div", undefined, "vh-wide vh-grid"); balancingBody.append(balancingSlot);
|
||||
const balancingControl = balancingEditor(balancingSlot, {
|
||||
@@ -515,10 +598,9 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
row.readBalancing = () => { if (!ownBalancing.checked) return null; balancingControl.validate(); const hash = balancingControl.hash(); return { algorithm: balancingControl.algorithm(), ...(hash ? { hash } : {}), sticky: balancingControl.sticky() }; };
|
||||
row.refreshBalancing = () => { renderGroup(); balancingControl.refresh(); };
|
||||
renderGroup();
|
||||
const handling = el("details", undefined, "vh-wide location-section"), handlingBody = el("div", undefined, "vh-grid"); handling.append(text("summary", "locationHandling"), handlingBody); body.append(handling);
|
||||
field(handlingBody, "location-error-target", "locationErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
|
||||
field(handlingBody, "location-error-statuses", "locationErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 });
|
||||
note(handlingBody, "locationErrorFallbackHelp");
|
||||
const handlingBody = whatGrid;
|
||||
errorFallbackFields(errorsPanel, "location-error", value.error_fallback, { target: "locationErrorFallbackTarget", statuses: "locationErrorFallbackStatuses" });
|
||||
note(errorsPanel, "locationErrorFallbackHelp");
|
||||
const rewriteMode = field(handlingBody, "location-rewrite-mode", "locationRewriteMode", value.rewrite?.mode || "preserve", "select", { values: [["preserve", "locationRewritePreserve"], ["strip_prefix", "locationRewriteStrip"], ["replace_prefix", "locationRewriteReplace"], ["regex", "locationRewriteRegex"]] });
|
||||
const rewriteValue = field(handlingBody, "location-rewrite-value", "locationRewriteValue", value.rewrite?.value || "", "text", { maxLength: 2048 });
|
||||
const returnBox = el("div", undefined, "vh-wide vh-grid location-return-box"); handlingBody.append(returnBox);
|
||||
@@ -531,9 +613,9 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
field(redirectBox, "location-redirect-pattern", "locationRedirectPattern", value.redirect?.rewrite_pattern || "", "text", { maxLength: 1024 });
|
||||
field(redirectBox, "location-redirect-query", "locationRedirectQuery", value.redirect?.preserve_query !== false, "checkbox", { switch: true });
|
||||
note(redirectBox, "locationRedirectHelp");
|
||||
note(handlingBody, "locationRewriteHelp");
|
||||
const rewriteHelp = note(handlingBody, "locationRewriteHelp");
|
||||
|
||||
const extra = el("details", undefined, "vh-wide location-section"), accessBody = el("div", undefined, "vh-grid"); extra.append(text("summary", "locationAccess"), accessBody); body.append(extra);
|
||||
const accessBody = accessPanel;
|
||||
const locationProfiles = subsection(accessBody, "vhAclProfile");
|
||||
const locationProfile = field(locationProfiles, "location-acl-profile", "locationAclProfile", value.acl_profile_id || "", "select");
|
||||
const locationNoProfile = text("option", "vhAclProfileNone"); locationNoProfile.value = "";
|
||||
@@ -549,15 +631,14 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
note(locationCountries, "locationCountryHelp");
|
||||
const locationAcl = subsection(accessBody, "vhLocationIpAclSection");
|
||||
const acl = aclEditor(locationAcl, value.acl, sync); row.readAcl = () => acl.read();
|
||||
const headerBox = el("details", undefined, "vh-wide location-section location-header-editor"), headerBody = el("div", undefined, "vh-grid"); headerBox.append(text("summary", "locationHeaders"), headerBody); body.append(headerBox);
|
||||
const headerBody = headersPanel; headerBody.classList.add("location-header-editor");
|
||||
const headerToolbar = el("div", undefined, "vh-wide location-header-toolbar"), visualPane = el("div", undefined, "vh-wide vh-grid"), jsonPane = el("div", undefined, "vh-wide vh-grid"); jsonPane.hidden = true;
|
||||
const visualButton = button("headersVisualBuilder", () => { visualPane.hidden = false; jsonPane.hidden = true; }), jsonButton = button("headersAdvancedJson", () => { visualPane.hidden = true; jsonPane.hidden = false; }), docsButton = button("documentation", () => openLocationHelp("headers"));
|
||||
headerToolbar.append(visualButton, jsonButton, docsButton); headerBody.append(headerToolbar, visualPane, jsonPane);
|
||||
const raw = field(jsonPane, "location-headers", "headersAdvancedJson", JSON.stringify(value.headers || {}, null, 2), "textarea", { rows: 8, maxLength: 65536 });
|
||||
const editor = headerEditors(visualPane, value.headers || {}, raw, sync, () => ({ location: str("location-id", row) || "main" })); row.readHeaders = () => editor.read();
|
||||
|
||||
const policyBox = el("details", undefined, "vh-wide location-section"), policyBody = el("div", undefined, "policy-detail-body");
|
||||
policyBox.append(text("summary", "policyTitle"), policyBody); body.append(policyBox);
|
||||
const policyBody = policyPanel; policyBody.classList.add("policy-detail-body");
|
||||
const policyEditor = window.rustProxyPolicy.create({ value: value.policy || {}, scope: "location", onChange: sync });
|
||||
policyBody.append(policyEditor.node); row.readPolicy = () => policyEditor.read();
|
||||
|
||||
@@ -576,46 +657,54 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
const moveDown = button("rtMoveDown", () => { if (row.nextElementSibling) { rows.insertBefore(row.nextElementSibling, row); sync(); } });
|
||||
actions.append(moveUp, moveDown, dedicated, button("remove", () => { row.remove(); sync(); })); body.append(actions);
|
||||
|
||||
let policyCount = (value.policy?.rules || []).length;
|
||||
const syncUi = () => {
|
||||
const isReturn = action.value === "return", isRedirect = action.value === "redirect", isWeb = action.value === "web_server", isProxy = action.value === "proxy", isRegex = match.value === "regex" || match.value === "regex_insensitive";
|
||||
match.disabled = internal.checked; path.disabled = internal.checked || match.value === "any";
|
||||
match.closest("label").hidden = internal.checked; path.closest("label").hidden = internal.checked || match.value === "any";
|
||||
const conditional = !internal.checked && conditions.count() > 0;
|
||||
conditionBox.hidden = internal.checked; conditionCacheNote.hidden = !conditional;
|
||||
if (conditional) cache.value = "";
|
||||
backend.disabled = !isProxy; cache.disabled = !isProxy || conditional; dedicated.disabled = !isProxy;
|
||||
const isGroup = isProxy && backend.value === LOCATION_GROUP, pinned = isProxy && !["", LOCATION_GROUP].includes(backend.value);
|
||||
balancing.hidden = !isProxy || pinned; groupBox.hidden = !isGroup;
|
||||
const balancingAvailable = isProxy && !pinned; setTabAvailable("backend", balancingAvailable); groupBox.hidden = !isGroup;
|
||||
ownBalancing.disabled = !isProxy || pinned; balancingSlot.hidden = !ownBalancing.checked; inheritNote.hidden = ownBalancing.checked;
|
||||
webService.disabled = !isWeb; webService.required = isWeb;
|
||||
backend.closest("label").hidden = !isProxy; webService.closest("label").hidden = !isWeb;
|
||||
rewriteMode.closest("label").hidden = isReturn || isRedirect; rewriteValue.closest("label").hidden = isReturn || isRedirect; rewriteHelp.hidden = isReturn || isRedirect;
|
||||
returnBox.hidden = !isReturn; redirectBox.hidden = !isRedirect; rewriteMode.disabled = isReturn || isRedirect; rewriteValue.disabled = isReturn || isRedirect || rewriteMode.value === "preserve" || rewriteMode.value === "strip_prefix";
|
||||
for (const option of rewriteMode.options) if (option.value === "regex") option.disabled = !isRegex;
|
||||
if (!isRegex && rewriteMode.value === "regex") rewriteMode.value = "preserve";
|
||||
path.placeholder = isRegex ? "^/api/v[0-9]+/" : "/api/";
|
||||
const id = str("location-id", row) || t("locationId"), pattern = internal.checked ? `@${id}` : match.value === "any" ? "*" : (str("location-path", row) || "/");
|
||||
const conditionNote = conditional ? ` · ${t("rtConditionCount").replace("{count}", String(conditions.count()))}` : "";
|
||||
summary.textContent = `${id} · ${internal.checked ? t("locationInternal") : t(`locationMatch_${match.value}`)} · ${pattern} · ${t(isReturn ? "locationReturnShort" : isRedirect ? "locationRedirectShort" : isWeb ? "locationWebServerShort" : "locationProxyShort")}${conditionNote}`;
|
||||
const enabledNow = yes("location-enabled", row); let actionText;
|
||||
row.classList.toggle("is-disabled", !enabledNow); sumState.title = t(enabledNow ? "enabled" : "notEnabled"); sumState.setAttribute("aria-label", sumState.title);
|
||||
sumId.textContent = id; sumMatch.textContent = internal.checked ? t("locationInternalShort") : t(`locationMatch_${match.value}`); sumMatch.classList.toggle("is-internal", internal.checked);
|
||||
sumPath.textContent = `${pattern}${conditionNote}`;
|
||||
|
||||
previewStatus.hidden = yes("location-enabled", row);
|
||||
previewValues.match.textContent = `${t(`locationMatch_${match.value}`)} · ${pattern}${conditionNote}`;
|
||||
if (isReturn) {
|
||||
const status = str("location-response-status", row) || "200", type = str("location-response-type", row) || "text/plain";
|
||||
previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`;
|
||||
previewValues.handling.textContent = `${t("locationReturnAction")}: HTTP ${status} · ${type} · ${t("locationPreviewBackendSkipped")}`; actionText = `${t("locationReturnAction")} ${status}`;
|
||||
previewValues.rewrite.textContent = "-";
|
||||
previewValues.cache.textContent = t("notEnabled");
|
||||
} else if (isRedirect) {
|
||||
const status = str("location-redirect-status", row) || "302", target = str("location-redirect-target", row) || "-", capture = str("location-redirect-pattern", row);
|
||||
previewValues.handling.textContent = `${t("locationRedirectAction")}: HTTP ${status} · ${target} · ${t("locationPreviewBackendSkipped")}`;
|
||||
previewValues.handling.textContent = `${t("locationRedirectAction")}: HTTP ${status} · ${target} · ${t("locationPreviewBackendSkipped")}`; actionText = `${t("locationRedirectAction")} ${status} → ${target}`;
|
||||
previewValues.rewrite.textContent = capture || "-";
|
||||
previewValues.cache.textContent = t("notEnabled");
|
||||
} else {
|
||||
if (isWeb) {
|
||||
const selected = webService.selectedOptions?.[0]?.textContent || t("webServiceSelect");
|
||||
previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`;
|
||||
previewValues.handling.textContent = `${t("locationWebServerAction")}: ${selected}`; actionText = `${t("locationWebServerShort")} → ${selected}`;
|
||||
previewValues.cache.textContent = t("notEnabled");
|
||||
} else {
|
||||
const selected = backend.value === LOCATION_GROUP ? `${t("locationBackendGroup")} (${[...groupSelected].join(", ") || "-"})` : backend.selectedOptions?.[0]?.textContent || t("locationPool");
|
||||
const algorithmLabel = ownBalancing.checked && !balancing.hidden ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : "";
|
||||
previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`;
|
||||
const shortTarget = backend.value === LOCATION_GROUP ? [...groupSelected].join(", ") || "-" : selected;
|
||||
const algorithmLabel = ownBalancing.checked && balancingAvailable ? ` · ${t(LB_ALGORITHMS.find(([v]) => v === balancingControl.algorithm())?.[1] || "vhAlgorithm")}${balancingControl.algorithm() === "hash" ? ` (${t(LB_SOURCES.find(([v]) => v === balancingControl.hash().source)?.[1] || "lbHash")})` : ""}` : "";
|
||||
previewValues.handling.textContent = `${t("locationProxyAction")}: ${selected}${algorithmLabel}`; actionText = `${t("locationProxyShort")} → ${shortTarget}`;
|
||||
previewValues.cache.textContent = t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit");
|
||||
}
|
||||
const rewriteLabels = { preserve: "locationRewritePreserve", strip_prefix: "locationRewriteStrip", replace_prefix: "locationRewriteReplace", regex: "locationRewriteRegex" };
|
||||
@@ -628,21 +717,40 @@ function locationsEditor(parent, values, onChange = changed) {
|
||||
const countryMode = str("location-country-mode", row); if (countryMode !== "off") accessParts.push(`${t("locationCountryMode")}: ${t(countryMode === "allow" ? "vhCountryAllow" : "vhCountryBlock")} ${lines(str("location-country-list", row)).join(", ")}`);
|
||||
if (yes("acl-use", row)) accessParts.push(t("locationPreviewCustomAcl"));
|
||||
previewValues.access.textContent = accessParts.length ? accessParts.join(" · ") : t("locationPreviewVhostAcl");
|
||||
let headerCount = 0;
|
||||
try {
|
||||
const headerValue = editor.read(), requestRules = headerValue.request?.length || 0, responseRules = headerValue.response?.length || 0;
|
||||
previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`;
|
||||
previewValues.headers.textContent = `${requestRules} ${t("locationPreviewRequestRules")} / ${responseRules} ${t("locationPreviewResponseRules")}`; headerCount = requestRules + responseRules;
|
||||
} catch { previewValues.headers.textContent = t("headersInvalid"); }
|
||||
// Row summary, headline and option tab states.
|
||||
sumAction.textContent = actionText || "";
|
||||
const fallbackTarget = str("location-error-target", row), fallbackStatuses = str("location-error-statuses", row).replace(/\s+/g, "");
|
||||
const visualRules = policyBody.querySelector(".policy-visual:not([hidden]) .policy-rules"); if (visualRules) policyCount = visualRules.querySelectorAll(":scope > .policy-rule").length;
|
||||
const cacheLabel = isProxy && !conditional ? t(cache.value === "on" ? "enabled" : cache.value === "off" ? "notEnabled" : "inherit") : "-";
|
||||
const ownLb = isProxy && balancingAvailable && (ownBalancing.checked || isGroup);
|
||||
const states = { access: accessParts.length ? String(accessParts.length) : "", headers: headerCount ? String(headerCount) : "", cache: isProxy && cache.value ? cacheLabel : "", errors: fallbackTarget ? `@${fallbackTarget}` : "", backend: isGroup ? t("locationChipGroup").replace("{count}", String(groupSelected.size)) : ownLb ? t("locationChipBalancing") : "", policy: policyCount ? String(policyCount) : "" };
|
||||
for (const [name, item] of tabs) { item.state.textContent = states[name] ? ` · ${states[name]}` : ""; item.tab.classList.toggle("is-set", Boolean(states[name])); }
|
||||
const chips = [];
|
||||
if (accessParts.length) chips.push(t("locationTabAccess"));
|
||||
if (headerCount) chips.push(`${t("locationTabHeaders")} ${headerCount}`);
|
||||
if (isProxy && !conditional && cache.value) chips.push(`Cache: ${cacheLabel}`);
|
||||
if (states.backend) chips.push(states.backend);
|
||||
if (policyCount) chips.push(`${t("policyTitle")} ${policyCount}`);
|
||||
sumChips.replaceChildren(...chips.map(label => el("span", label, "loc-chip")));
|
||||
if (fallbackTarget) { const chip = el("span", `${t("locationChipFallback")} ${fallbackStatuses} → @${fallbackTarget}`, "loc-chip is-fallback"); sumChips.append(chip); }
|
||||
headline.textContent = `${internal.checked ? `@${id} (${t("locationInternalShort")})` : pattern}${conditionNote} → ${actionText || "-"}${fallbackTarget ? ` · ${t("locationChipFallback")} ${fallbackStatuses} → @${fallbackTarget}` : ""}${enabledNow ? "" : ` · ${t("notEnabled")}`}`;
|
||||
};
|
||||
row.addEventListener("input", () => { syncUi(); sync(); }); row.addEventListener("change", () => { syncUi(); sync(); });
|
||||
selectTab(value.backend_ids?.length || value.load_balancing ? "backend" : "access");
|
||||
rows.append(row); syncUi();
|
||||
}
|
||||
for (const value of values) add(value);
|
||||
for (const value of values) add(value, false, false);
|
||||
const bottom = el("div", undefined, "vh-wide location-toolbar location-toolbar-bottom"); bottom.append(button("locationAdd", () => { add(); sync(); }, "primary")); parent.append(bottom);
|
||||
const refreshMembers = () => { for (const select of rows.querySelectorAll('[name="location-backend"]')) memberOptions(select); for (const row of rows.children) row.refreshBalancing?.(); };
|
||||
form.querySelector(".vh-members").addEventListener("input", refreshMembers); form.querySelector(".vh-members").addEventListener("change", refreshMembers);
|
||||
readRows.set = data => {
|
||||
validateLocations(data); const previous = [...rows.childNodes]; reloading = true;
|
||||
try { rows.replaceChildren(); for (const value of data) add(value); readRows(); tester?.run(); }
|
||||
try { rows.replaceChildren(); for (const value of data) add(value, false, false); renumber(); readRows(); tester?.run(); }
|
||||
catch (error) { rows.replaceChildren(...previous); throw error; }
|
||||
finally { reloading = false; }
|
||||
};
|
||||
|
||||
@@ -365,9 +365,9 @@ function load(value = defaults(), migrationIds = [], show = true) {
|
||||
field(uaBlockingFields, "ua-block-patterns", "vhUaBlockPatterns", (uaBlock.patterns || []).join("\n"), "textarea", { rows: 4, maxLength: 32768 });
|
||||
note(uaBlockingFields, "vhUaBlockHelp");
|
||||
g = group("vhLocations");
|
||||
field(g, "main-error-target", "vhErrorFallbackTarget", value.error_fallback?.target || "", "text", { maxLength: 64, pattern: "[A-Za-z0-9_\\-]{0,64}" });
|
||||
field(g, "main-error-statuses", "vhErrorFallbackStatuses", (value.error_fallback?.statuses || [404]).join(", "), "text", { maxLength: 64 });
|
||||
note(g, "vhErrorFallbackHelp");
|
||||
const fallbackFields = subsection(g, "vhErrorFallbackSection");
|
||||
errorFallbackFields(fallbackFields, "main-error", value.error_fallback, { target: "vhErrorFallbackTarget", statuses: "vhErrorFallbackStatuses" });
|
||||
note(fallbackFields, "vhErrorFallbackHelp");
|
||||
const pathsJson = jsonDrawer(g, { name: "paths", titleKey: "vhLocationsJson", helpKey: "vhLocationsJsonHelp", value: value.routes || [], maxLength: 131072, validate: validateLocations, apply: data => locationsReader.set(data) });
|
||||
locationsReader = locationsEditor(g, value.routes || [], () => { changed(); pathsJson.refresh(); });
|
||||
g.append(pathsJson.node);
|
||||
|
||||
Reference in new issue
Block a user