Files
RustProxy/src/admin/web/acl-picker.js
T
2026-11-16 13:46:24 +01:00

306 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
window.rustProxyAclPicker = (() => {
const LIMIT = 8;
const profiles = () => envelope?.config?.acl_profiles || [];
const chosenIds = root => [...(root?.querySelectorAll('.acl-picker-option input[type="checkbox"]:checked') || [])].map(input => input.value);
const preview = profile => {
const rules = profile.acl?.rules || [], country = profile.country_access || {};
const lines = rules.slice(0, 3).map(rule => `${rule.action === "deny" ? t("deny") : t("allow")} ${rule.network}`);
if (rules.length > 3) lines.push(`+${rules.length - 3} ${t("aclPickerMoreRules")}`);
if (country.mode === "allow" || country.mode === "block") {
const codes = (country.countries || []).slice(0, 5).join(", ");
const extra = (country.countries || []).length - 5;
lines.push(`${t(country.mode === "block" ? "aclPickerBlockedCountries" : "aclPickerAllowedCountries")}: ${codes}${extra > 0 ? ` +${extra}` : ""}`);
}
if (!lines.length) lines.push(t(profile.acl ? "aclPickerNoRules" : "aclPickerNoIpRules"));
return lines.join(" · ");
};
function create(selected = [], className = "") {
const root = el("div", undefined, `acl-picker ${className}`.trim());
const details = el("details", undefined, "acl-picker-details"), summary = el("summary", undefined, "acl-picker-summary");
const heading = el("span", t("aclPickerChoose"), "acl-picker-heading");
const counter = el("span", "", "acl-picker-counter");
summary.append(heading, counter); details.append(summary);
const dropdown = el("div", undefined, "acl-picker-dropdown");
const search = el("input", "", "acl-picker-search"); search.type = "search"; search.placeholder = t("aclPickerSearch"); search.setAttribute("aria-label", t("aclPickerSearch"));
const options = el("div", undefined, "acl-picker-options");
const empty = el("p", t("aclPickerNoMatches"), "fine acl-picker-empty");
const maxHint = el("small", t("aclPickerLimit"), "fine acl-picker-limit");
dropdown.append(search, options, empty, maxHint); details.append(dropdown);
const selectedTags = el("div", undefined, "acl-picker-selected");
root.append(details, selectedTags);
const items = profiles();
const checks = new Map(), selectedSet = new Set(selected);
if (!items.length) {
const noProfiles = el("p", t("aclPickerNoProfiles"), "fine");
options.append(noProfiles); search.disabled = true;
}
for (const profile of items) {
const label = el("label", undefined, "acl-picker-option");
const check = el("input"); check.type = "checkbox"; check.value = profile.id; check.checked = selectedSet.has(profile.id);
const content = el("span", undefined, "acl-picker-option-content");
const headingRow = el("span", undefined, "acl-picker-option-heading");
const name = el("strong", profile.name || profile.id), identity = el("code", profile.id, "acl-picker-id");
const badge = el("span", t(!profile.acl ? "aclPickerNoIpRules" : profile.acl.default === "allow" ? "aclPickerDefaultAllow" : "aclPickerDefaultDeny"), `acl-picker-policy ${profile.acl?.default === "deny" ? "is-deny" : profile.acl?.default === "allow" ? "is-allow" : "is-none"}`);
headingRow.append(name, identity, badge);
content.append(headingRow, el("small", preview(profile), "acl-picker-rule-preview"));
label.append(check, content); options.append(label); checks.set(profile.id, check);
const allRules = (profile.acl?.rules || []).map(rule => `${rule.action} ${rule.network}`).join(" ");
const countries = (profile.country_access?.countries || []).join(" ");
const searchText = `${profile.name || ""} ${profile.id} ${allRules} ${countries}`.toLocaleLowerCase();
label.dataset.search = searchText;
}
const syncSearch = () => {
const query = search.value.trim().toLocaleLowerCase(); let visible = 0;
for (const label of options.querySelectorAll(".acl-picker-option")) {
label.hidden = !!query && !label.dataset.search.includes(query);
if (!label.hidden) visible++;
}
empty.hidden = visible > 0 || items.length === 0;
};
const sync = () => {
const ids = chosenIds(root), full = ids.length >= LIMIT;
counter.textContent = `${ids.length}/${LIMIT}`;
heading.textContent = ids.length ? t("aclPickerSelected").replace("{count}", ids.length) : t("aclPickerChoose");
selectedTags.replaceChildren();
for (const id of ids) {
const profile = items.find(item => item.id === id);
const tag = el("span", undefined, "acl-picker-tag");
const label = el("span", profile?.name || id); label.title = preview(profile || {});
const remove = el("button", "×", "acl-picker-remove"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${profile?.name || id}`);
remove.addEventListener("click", () => { const box = checks.get(id); box.checked = false; box.dispatchEvent(new Event("change", { bubbles: true })); });
tag.append(label, remove); selectedTags.append(tag);
}
if (!ids.length) selectedTags.append(el("span", t("aclPickerNone"), "fine acl-picker-no-selection"));
for (const check of checks.values()) check.disabled = full && !check.checked;
maxHint.hidden = !full;
};
options.addEventListener("change", event => { if (event.target.matches('input[type="checkbox"]')) sync(); });
search.addEventListener("input", syncSearch);
search.addEventListener("keydown", event => { if (event.key === "Escape") { search.value = ""; syncSearch(); details.open = false; summary.focus(); } });
root.select = ids => { for (const [id, box] of checks) box.checked = ids.includes(id); sync(); };
root.setDisabled = disabled => { root.classList.toggle("is-disabled", disabled); details.open = details.open && !disabled; summary.tabIndex = disabled ? -1 : 0; summary.setAttribute("aria-disabled", String(disabled)); };
syncSearch(); sync(); return root;
}
return { create, read: chosenIds, count: root => chosenIds(root).length };
})();
window.rustProxyChoicePicker = (() => {
function create(options) {
const limit = options.limit || 16, labels = options.labels || {};
const label = (key, fallback) => labels[key] ? t(labels[key]) : t(fallback);
const root = el("div", undefined, `acl-picker choice-picker ${options.className || ""}`.trim());
const details = el("details", undefined, "acl-picker-details"), summary = el("summary", undefined, "acl-picker-summary");
const heading = el("span", "", "acl-picker-heading"), counter = el("span", "", "acl-picker-counter");
summary.append(heading, counter); details.append(summary);
const dropdown = el("div", undefined, "acl-picker-dropdown");
const search = el("input", "", "acl-picker-search"); search.type = "search"; search.placeholder = label("search", "aclPickerSearch"); search.setAttribute("aria-label", search.placeholder);
const optionsBox = el("div", undefined, "acl-picker-options"), empty = el("p", label("noMatches", "aclPickerNoMatches"), "fine acl-picker-empty");
const maxHint = el("small", t("aclPickerLimit"), "fine acl-picker-limit");
dropdown.append(search, optionsBox, empty, maxHint); details.append(dropdown);
const selectedTags = el("div", undefined, "acl-picker-selected"); root.append(details, selectedTags);
// Option rows are built on the first open: long lists (countries) would
// otherwise add thousands of DOM nodes per picker. `state` is the source of
// truth for every option; `checks` holds only rendered checkboxes.
const items = [...(options.items || [])], state = new Map(), checks = new Map(), order = [];
let rendered = false;
const isChosen = id => state.get(id) === true;
const renderOption = item => {
const row = el("label", undefined, "acl-picker-option"), check = el("input"); check.type = "checkbox"; check.value = item.id; check.checked = isChosen(item.id);
const content = el("span", undefined, "acl-picker-option-content"), headingRow = el("span", undefined, "acl-picker-option-heading");
headingRow.append(el("strong", item.title || item.id));
if (item.title && item.title !== item.id && !item.title.startsWith(`${item.id} `)) headingRow.append(el("code", item.id, "acl-picker-id"));
if (item.badge) headingRow.append(el("span", item.badge, `acl-picker-policy ${item.badgeClass || "is-none"}`));
content.append(headingRow); if (item.detail) content.append(el("small", item.detail, "acl-picker-rule-preview"));
row.append(check, content); row.dataset.search = `${item.id} ${item.title || ""} ${item.search || ""} ${item.detail || ""}`.toLocaleLowerCase();
optionsBox.append(row); checks.set(item.id, check);
};
const addOption = (item, checked) => {
if (!state.has(item.id)) { state.set(item.id, false); if (!items.includes(item)) items.push(item); if (rendered) renderOption(item); }
if (checked && !isChosen(item.id)) { state.set(item.id, true); order.push(item.id); const box = checks.get(item.id); if (box) box.checked = true; }
};
const renderOptions = () => { if (rendered) return; rendered = true; for (const item of items) renderOption(item); syncSearch(); sync(); };
const setChosen = (id, value) => { state.set(id, value); const box = checks.get(id); if (box) box.checked = value; };
const selected = [...new Set(options.selected || [])];
for (const item of items.slice()) addOption(item, false);
for (const id of selected) addOption(items.find(item => item.id === id) || { id, title: id, detail: options.unknownDetail ? t(options.unknownDetail) : "" }, true);
const chosen = () => order.filter(isChosen);
const syncSearch = () => {
const query = search.value.trim().toLocaleLowerCase(); let visible = 0;
for (const row of optionsBox.querySelectorAll(".acl-picker-option")) { row.hidden = !!query && !row.dataset.search.includes(query); if (!row.hidden) visible++; }
if (!rendered) visible = items.length;
empty.hidden = visible > 0 || (!query && !items.length);
empty.textContent = query && options.custom ? label("addHint", "choicePickerAddHint").replace("{value}", search.value.trim()) : label("noMatches", "aclPickerNoMatches");
if (!items.length && !query) { empty.hidden = false; empty.textContent = label("empty", "choicePickerEmpty"); }
};
const sync = () => {
for (const [id, box] of checks) state.set(id, box.checked);
for (const [id, value] of state) { const index = order.indexOf(id); if (value && index < 0) order.push(id); if (!value && index >= 0) order.splice(index, 1); }
const ids = chosen(), full = ids.length >= limit;
counter.textContent = `${ids.length}/${limit}`;
heading.textContent = ids.length ? label("selected", "aclPickerSelected").replace("{count}", ids.length) : label("choose", "aclPickerChoose");
selectedTags.replaceChildren();
ids.forEach((id, index) => {
const item = items.find(entry => entry.id === id), tag = el("span", undefined, `acl-picker-tag${index === 0 && options.markFirst ? " is-primary" : ""}`);
const text = el("span", item?.title || id); text.title = item?.detail || id;
if (index === 0 && options.markFirst) tag.title = t(options.markFirst);
const remove = el("button", "×", "acl-picker-remove"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${item?.title || id}`);
remove.addEventListener("click", () => { const box = checks.get(id); if (box) { box.checked = false; box.dispatchEvent(new Event("change", { bubbles: true })); return; } setChosen(id, false); sync(); root.dispatchEvent(new Event("change", { bubbles: true })); });
tag.append(text);
if (index > 0 && options.markFirst && options.makeFirst) {
const promote = el("button", "★", "acl-picker-promote"); promote.type = "button"; promote.dataset.uiIconName = "none"; promote.title = t(options.makeFirst); promote.setAttribute("aria-label", `${t(options.makeFirst)}: ${item?.title || id}`);
promote.addEventListener("click", () => { order.splice(order.indexOf(id), 1); order.unshift(id); sync(); root.dispatchEvent(new Event("change", { bubbles: true })); });
tag.append(promote);
}
tag.append(remove); selectedTags.append(tag);
});
if (!ids.length) selectedTags.append(el("span", label("none", "aclPickerNone"), "fine acl-picker-no-selection"));
for (const box of checks.values()) box.disabled = full && !box.checked;
maxHint.hidden = !full; root.dispatchEvent(new CustomEvent("choicechange", { detail: ids }));
};
const addCustom = () => {
const raw = search.value.trim(); if (!raw || !options.custom) return;
const values = raw.split(/[\s,;]+/).filter(Boolean);
for (const value of values) {
let item; try { item = options.custom(value); } catch (error) { toast(error.message, true); return; }
if (!item) continue;
if (chosen().length >= limit && !isChosen(item.id)) { toast(t("aclPickerLimit"), true); break; }
addOption(items.find(entry => entry.id === item.id) || item, false); setChosen(item.id, true);
}
search.value = ""; syncSearch(); sync(); root.dispatchEvent(new Event("change", { bubbles: true }));
};
details.addEventListener("toggle", () => { if (details.open) renderOptions(); });
search.addEventListener("focus", renderOptions);
optionsBox.addEventListener("change", event => { if (event.target.matches('input[type="checkbox"]')) sync(); });
search.addEventListener("input", syncSearch);
search.addEventListener("keydown", event => {
if (event.key === "Enter") { event.preventDefault(); if (options.custom) addCustom(); else { const first = [...optionsBox.querySelectorAll(".acl-picker-option:not([hidden]) input:not(:disabled)")][0]; if (first) { first.checked = !first.checked; first.dispatchEvent(new Event("change", { bubbles: true })); } } }
if (event.key === "Escape") { search.value = ""; syncSearch(); details.open = false; summary.focus(); }
});
search.addEventListener("blur", () => { if (options.custom && search.value.trim()) addCustom(); });
root.read = chosen;
root.setDisabled = disabled => { root.classList.toggle("is-disabled", disabled); details.open = details.open && !disabled; summary.tabIndex = disabled ? -1 : 0; summary.setAttribute("aria-disabled", String(disabled)); };
root.select = ids => { for (const id of state.keys()) setChosen(id, ids.includes(id)); order.length = 0; order.push(...ids.filter(id => state.has(id))); sync(); };
syncSearch(); sync(); return root;
}
return { create, read: root => root?.read?.() || [] };
})();
window.rustProxyChipInput = (() => {
const CIDR = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}(?:\/(?:3[0-2]|[12]?\d))?|[0-9a-fA-F:]*:[0-9a-fA-F:.]*(?:\/(?:12[0-8]|1[01]\d|[1-9]?\d))?)$/;
function create(options = {}) {
const box = el("div", undefined, `host-chip-editor ${options.className || ""}`.trim()), input = document.createElement("input");
input.type = "text"; input.maxLength = options.maxLength || 128; input.placeholder = options.placeholder || ""; input.spellcheck = false;
if (options.label) input.setAttribute("aria-label", options.label);
const values = [], limit = options.limit || 64;
const changed = () => box.dispatchEvent(new Event("change", { bubbles: true }));
const normalize = raw => { const value = String(raw || "").trim(); if (!value) return null; if (options.validate) { const result = options.validate(value); if (result === false) throw fieldError(input, options.invalidMessage || t("invalidValue")); if (typeof result === "string") return result; } return value; };
const sync = () => {
box.querySelectorAll(".host-chip").forEach(node => node.remove());
for (const value of values) {
const chip = el("span", undefined, "host-chip"); chip.append(el("span", value));
const remove = el("button", "×"); remove.type = "button"; remove.setAttribute("aria-label", `${t("remove")} ${value}`);
remove.addEventListener("click", () => { values.splice(values.indexOf(value), 1); sync(); changed(); });
chip.append(remove); box.insertBefore(chip, input);
}
};
const add = (raw, notify = true) => { const value = normalize(raw); if (!value || values.includes(value)) return; if (values.length >= limit) throw fieldError(input, options.limitMessage || t("aclPickerLimit")); values.push(value); sync(); if (notify) changed(); };
const consume = raw => { for (const part of String(raw).split(/[\s,;]+/).filter(Boolean)) add(part); input.value = ""; };
const guarded = raw => { try { consume(raw); } catch (error) { toast(error.message, true); } };
input.addEventListener("keydown", event => { if (event.key === "Enter" || event.key === ",") { event.preventDefault(); guarded(input.value); } });
input.addEventListener("blur", () => { if (input.value.trim()) guarded(input.value); });
input.addEventListener("paste", event => { const value = event.clipboardData?.getData("text") || ""; if (!/[\s,;]/.test(value.trim())) return; event.preventDefault(); guarded(value); });
box.append(input);
for (const value of options.values || []) { try { add(value, false); } catch { } }
box.read = () => { if (input.value.trim()) consume(input.value); return [...values]; };
box.set = list => { values.length = 0; for (const value of list || []) { try { add(value, false); } catch { } } sync(); };
box.input = input;
return box;
}
const validCidr = value => CIDR.test(value);
return { create, validCidr };
})();
window.rustProxyCountryPicker = (() => {
const CODES = "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS XK YE YT ZA ZM ZW".split(" ");
// Country names are resolved once per language: constructing Intl.DisplayNames
// for every lookup was a large part of rendering many country pickers.
const countryNames = new Map();
const nameOf = code => {
const lang = document.documentElement.lang || "en";
let names = countryNames.get(lang);
if (!names) { let display = null; try { display = new Intl.DisplayNames([lang], { type: "region" }); } catch { /* unsupported locale */ } names = { display, cache: new Map() }; countryNames.set(lang, names); }
if (!names.cache.has(code)) { let name = code; try { name = names.display?.of(code) || code; } catch { /* unknown region */ } names.cache.set(code, name); }
return names.cache.get(code);
};
const parse = text => [...new Set(String(text || "").split(/[\s,;]+/).map(value => value.trim().toUpperCase()).filter(Boolean))];
function attach(textarea, options = {}) {
if (!textarea || textarea.dataset.countryPicker) return null;
textarea.dataset.countryPicker = "1"; textarea.hidden = true;
const host = el("div", undefined, "country-picker-host"); textarea.after(host);
let picker = null, writing = false;
const build = () => {
const items = CODES.map(code => ({ id: code, title: `${code} · ${nameOf(code)}`, search: nameOf(code) }));
picker = window.rustProxyChoicePicker.create({
className: "country-picker", selected: parse(textarea.value), items, limit: options.limit || 250,
labels: { choose: "countryPickerChoose", selected: "countryPickerSelected", none: "countryPickerNone", search: "countryPickerSearch", addHint: "countryPickerAddHint", empty: "countryPickerEmpty" },
custom: raw => {
const text = String(raw || "").trim(); if (!text) return null;
const code = text.toUpperCase();
if (/^[A-Z]{2}$/.test(code)) return { id: code, title: `${code} · ${nameOf(code)}` };
const query = text.toLocaleLowerCase(), matches = CODES.filter(item => nameOf(item).toLocaleLowerCase().includes(query));
const exact = matches.find(item => nameOf(item).toLocaleLowerCase() === query) || (matches.length === 1 ? matches[0] : null);
return exact ? { id: exact, title: `${exact} · ${nameOf(exact)}` } : null;
},
});
picker.addEventListener("choicechange", event => { if (writing) return; const value = (event.detail || []).join("\n"); if (value === textarea.value) return; textarea.value = value; textarea.dispatchEvent(new Event("input", { bubbles: true })); });
host.replaceChildren(picker);
picker.setDisabled(textarea.disabled);
};
const refresh = () => { writing = true; try { build(); } finally { writing = false; } };
refresh();
new MutationObserver(() => picker?.setDisabled(textarea.disabled)).observe(textarea, { attributes: true, attributeFilter: ["disabled"] });
return { refresh, host };
}
return { attach, codes: CODES, nameOf };
})();
window.rustProxyMethodPicker = (() => {
const METHODS = [
["GET", "methodGet"], ["HEAD", "methodHead"], ["POST", "methodPost"], ["PUT", "methodPut"], ["PATCH", "methodPatch"], ["DELETE", "methodDelete"],
["OPTIONS", "methodOptions"], ["CONNECT", "methodConnect"], ["TRACE", "methodTrace"], ["TRACK", "methodTrack"], ["PURGE", "methodPurge"], ["BAN", "methodBan"],
["PROPFIND", "methodWebdav"], ["PROPPATCH", "methodWebdav"], ["MKCOL", "methodWebdav"], ["COPY", "methodWebdav"], ["MOVE", "methodWebdav"], ["LOCK", "methodWebdav"], ["UNLOCK", "methodWebdav"],
["SEARCH", "methodWebdav"], ["REPORT", "methodWebdav"], ["MKCALENDAR", "methodWebdav"],
];
const TOKEN = /^[A-Z0-9!#$%&'*+.^_`|~-]{1,32}$/;
const parse = text => [...new Set(String(text || "").split(/[\s,;]+/).map(value => value.trim().toUpperCase()).filter(Boolean))];
function attach(textarea) {
if (!textarea || textarea.dataset.methodPicker) return null;
textarea.dataset.methodPicker = "1"; textarea.hidden = true;
const wrapper = textarea.parentElement;
if (wrapper?.tagName === "LABEL") { const box = el("div", undefined, wrapper.className); box.append(...wrapper.childNodes); wrapper.replaceWith(box); }
const host = el("div", undefined, "method-picker-host"); textarea.after(host);
let picker = null, writing = false;
const build = () => {
picker = window.rustProxyChoicePicker.create({
className: "method-picker", selected: parse(textarea.value), limit: 64, unknownDetail: "methodCustom",
items: METHODS.map(([id, key]) => ({ id, title: id, detail: t(key) })),
labels: { choose: "methodPickerChoose", selected: "methodPickerSelected", none: "methodPickerNone", search: "methodPickerSearch", addHint: "methodPickerAddHint", empty: "methodPickerEmpty" },
custom: raw => {
const id = String(raw || "").trim().toUpperCase(); if (!id) return null;
if (!TOKEN.test(id)) throw new Error(t("methodPickerInvalid").replace("{value}", raw));
return { id, title: id, detail: t("methodCustom") };
},
});
picker.addEventListener("choicechange", event => { if (writing) return; const value = (event.detail || []).join("\n"); if (value === textarea.value) return; textarea.value = value; textarea.dispatchEvent(new Event("input", { bubbles: true })); textarea.dispatchEvent(new Event("change", { bubbles: true })); });
host.replaceChildren(picker);
picker.setDisabled(textarea.disabled);
};
const refresh = () => { writing = true; try { build(); } finally { writing = false; } };
refresh();
new MutationObserver(() => picker?.setDisabled(textarea.disabled)).observe(textarea, { attributes: true, attributeFilter: ["disabled"] });
return { refresh, host };
}
return { attach, methods: METHODS.map(([id]) => id) };
})();