From 40d9989c9884ac8f620eb06ada62adc84af41b43 Mon Sep 17 00:00:00 2001 From: Sam Latsin Date: Thu, 29 Oct 2026 21:23:26 +0300 Subject: [PATCH] Fixed graph layout --- README.md | 13 ++-- luci/graph.js | 151 ++++++++++++++++++++++++++++++++------------ tools/test-graph.js | 13 ++++ 3 files changed, 132 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index 4a2eeed..4ee3033 100644 --- a/README.md +++ b/README.md @@ -117,11 +117,14 @@ Connect, и сессия освобождается за секунды — мо LuCI → **Службы → mihomo-kit → Граф** — собранный профиль картинкой, слева направо: правила (сверху вниз — в порядке, в котором mihomo их проверяет) → группы → подписки и -свои серверы → через что они подключаются (`dialer-proxy`, фиолетовый пунктир). Зелёный -пунктир — через что качается подписка (`proxy:` провайдера, обычно `BOOT-AUTO`) и -`<имя>-my`, читающий файл основной подписки. На рёбрах группа → подписка — фильтры -(`∋` filter, `∌` exclude-filter). Правило в `DIRECT`/`REJECT` заканчивается на самом -правиле. +свои серверы → через что они подключаются → выходы. Выходы — последняя колонка: `DIRECT` +и прокси `type: direct` (`CSQTT`, интерфейс `csqtt0`). Фиолетовый пунктир — `dialer-proxy`, +серый — к серверу напрямую (у прокси и подписки нет `dialer-proxy`: Tailscale и OpenVPN на +`main`). Зелёный — через что качается подписка (`proxy:` провайдера, обычно `BOOT-AUTO`) и +`<имя>-my`, читающий файл основной подписки. То, куда правила не ведут (`BOOT-AUTO`, `BOOT`, +seed-ноды), — под чертой «служебное». Правило в `DIRECT`/`REJECT` заканчивается на самом +правиле. Фильтры групп (`∋` filter, `∌` exclude-filter) видны на рёбрах при наведении; +⛶ — на весь экран. Для запущенного профиля поверх схемы — живое состояние из API mihomo (раз в 3 секунды, пока вкладка открыта): что выбрано в каждой группе сейчас (синее) с задержкой, сколько нод diff --git a/luci/graph.js b/luci/graph.js index 07eb1e6..6e186eb 100644 --- a/luci/graph.js +++ b/luci/graph.js @@ -15,13 +15,13 @@ // --- model ----------------------------------------------------------------- - // outbounds mihomo has without a config entry: a node of their own per group or proxy - // using one (rank right after it), not one node every edge crosses the page to; a rule - // to one has no node at all + // outbounds mihomo has without a config entry: one node each in the last column ("exits", + // with the proxies of type direct such as CSQTT); a rule to one ends at the rule var BUILTIN = { 'DIRECT': 1, 'REJECT': 1, 'REJECT-DROP': 1, 'PASS': 1, 'COMPATIBLE': 1, 'GLOBAL': 1 }; var LOGIC = { 'AND': 1, 'OR': 1, 'NOT': 1, 'SUB-RULE': 1 }; - // edges that place nodes left to right; fetch / file are drawn over the layout - var RANKED = { route: 1, member: 1, use: 1, dialer: 1 }; + // edges that place nodes left to right; fetch / file are drawn over the layout. + // wan: a proxy or subscription without dialer-proxy connects to its server directly + var RANKED = { route: 1, member: 1, use: 1, dialer: 1, wan: 1 }; // "AND,((DOMAIN,a),(NETWORK,UDP)),X" -> parts split on commas outside parentheses function splitTop(s) { @@ -85,6 +85,8 @@ } function proxySub(p) { + if (p.type == 'direct') + return 'выход' + (p['interface-name'] ? ' через ' + p['interface-name'] : ''); var s = p.type || '?'; if (p.server) s += ' · ' + p.server; @@ -96,13 +98,13 @@ } // model(cfg) -> { nodes: {id: node}, list: [node], edges: [edge], ... } - // node { id, kind: rule|group|provider|proxy|builtin|missing, label, sub, data } - // edge { from, to, kind: route|member|use|dialer|fetch|file, label } + // node { id, kind: rule|group|provider|proxy|builtin|missing, label, sub, exit, data } + // edge { from, to, kind: route|member|use|dialer|wan|fetch|file, label } // ids: r: rules, g: groups, p: proxies, v: providers, - // b:@ built-in outbounds + // b: built-in outbounds; exit: DIRECT, REJECT, proxies of type direct (last column) function model(cfg) { cfg = cfg || {}; - var m = { nodes: {}, list: [], edges: [], byPair: {}, ruleIndex: {}, warnings: [] }; + var m = { nodes: {}, list: [], edges: [], byPair: {}, ruleIndex: {}, dialerOf: {}, warnings: [] }; var groups = {}, proxies = {}, providers = cfg['proxy-providers'] || {}; var ruleProviders = cfg['rule-providers'] || {}; (cfg['proxy-groups'] || []).forEach(function(g) { if (g && g.name != null) groups[g.name] = g; }); @@ -121,6 +123,8 @@ var edge = function(from, to, kind, label) { var e = { from: from, to: to, kind: kind, label: label || '' }; m.edges.push(e); + if (kind == 'dialer' || kind == 'wan') + m.dialerOf[from] = to; m.byPair[from + '\n' + to] = m.byPair[from + '\n' + to] || e; return e; }; @@ -131,16 +135,15 @@ return 'g:' + name; if (proxies[name]) return 'p:' + name; - var id = 'b:' + name + '@' + user; + var id = 'b:' + name; if (BUILTIN[name]) - node(id, 'builtin', name); + node(id, 'builtin', name, name == 'DIRECT' ? 'напрямую' : '').exit = true; else { node(id, 'missing', name, 'нет в конфиге'); m.warnings.push(name + ': нет такой группы или прокси (' + user + ')'); } return id; }; - m.ref = ref; // rules: one node per run of the same type and target var rules = (cfg.rules || []).map(parseRule), blocks = []; @@ -199,8 +202,7 @@ var sub = d.type == 'http' ? maskUrl(d.url) : d.type == 'file' ? 'файл ' + (d.path || '') : d.type || ''; node(id, 'provider', v, sub, { def: d }).sub = sub; var dialer = d.override && d.override['dialer-proxy']; - if (dialer) - edge(id, ref(dialer, id), 'dialer', 'через'); + edge(id, ref(dialer || 'DIRECT', id), dialer ? 'dialer' : 'wan', dialer ? 'через' : 'напрямую'); if (d.type == 'http' && d.proxy) edge(id, ref(d.proxy, id), 'fetch', 'качается через'); // [MY] nodes: a file provider reading what another one downloads @@ -212,9 +214,13 @@ if (!p || p.name == null) return; var id = 'p:' + p.name; - node(id, 'proxy', p.name, proxySub(p), { def: p }); - if (p['dialer-proxy']) + var n = node(id, 'proxy', p.name, proxySub(p), { def: p }); + if (p.type == 'direct') + n.exit = true; + else if (p['dialer-proxy']) edge(id, ref(p['dialer-proxy'], id), 'dialer', 'через'); + else + edge(id, ref('DIRECT', id), 'wan', 'напрямую'); }); return m; } @@ -247,12 +253,14 @@ return out; } - // layout(m, measure) -> { nodes: {id: {x, y, w, h}}, edges: [{e, pts}], width, height } + // layout(m, measure) -> { nodes: {id: {x, y, w, h, aux}}, edges: [{e, pts}], width, height, lane } // Sugiyama-style: ranks by the longest path from the rules, dummy nodes on long edges, // barycenter sweeps for the order, then y as close to the neighbours as the order allows. + // Exits take the last column; what no rule leads to (BOOT-AUTO, seeds: downloading the + // subscriptions) goes to a lane under the rest, its top at lane. function layout(m, measure) { measure = measure || function(s, px) { return String(s).length * px * 0.6; }; - var NODE_H = 36, GAP_Y = 8, GAP_X = 90, DUMMY_H = 6; + var NODE_H = 36, GAP_Y = 8, GAP_X = 90, DUMMY_H = 16, LANE_GAP = 70; var out = {}, succ = {}, pred = {}; m.list.forEach(function(n) { succ[n.id] = []; pred[n.id] = []; }); m.edges.forEach(function(e) { @@ -293,14 +301,28 @@ }); } - // layers with dummies; segs: per ranked edge the chain of ids it passes + // exits: one column after everything else var maxRank = 0, layers = [], chain = []; - m.list.forEach(function(n) { maxRank = Math.max(maxRank, rank[n.id]); }); + m.list.forEach(function(n) { if (!n.exit) maxRank = Math.max(maxRank, rank[n.id]); }); + if (m.list.some(function(n) { return n.exit; })) + maxRank++; + m.list.forEach(function(n) { if (n.exit) rank[n.id] = maxRank; }); + // the lane: neither reached from the rules nor an exit + var reached = {}, stack = m.list.filter(function(n) { return n.kind == 'rule'; }).map(function(n) { return n.id; }); + while (stack.length) { + var cur = stack.pop(); + if (reached[cur]) + continue; + reached[cur] = 1; + stack = stack.concat(succ[cur]); + } + + // layers with dummies; chain: per ranked edge the nodes it passes for (var r = 0; r <= maxRank; r++) layers.push([]); var info = {}; m.list.forEach(function(n) { - info[n.id] = { id: n.id, rank: rank[n.id], up: [], down: [], h: NODE_H, node: n }; + info[n.id] = { id: n.id, rank: rank[n.id], up: [], down: [], h: NODE_H, node: n, aux: !reached[n.id] && !n.exit }; }); // first seen from the rules, top to bottom: a sensible starting order var seen = {}, queue = m.list.filter(function(n) { return n.kind == 'rule'; }).map(function(n) { return n.id; }); @@ -327,7 +349,7 @@ } var c = [ a ], prev = a; for (var rr = a.rank + 1; rr < b.rank; rr++) { - var d = { id: '~' + (dn++), rank: rr, up: [ prev ], down: [], h: DUMMY_H, dummy: true }; + var d = { id: '~' + (dn++), rank: rr, up: [ prev ], down: [], h: DUMMY_H, dummy: true, aux: a.aux }; prev.down.push(d); layers[rr].push(d); c.push(d); @@ -350,7 +372,7 @@ var sweep = function(r, dir) { var l = layers[r]; l.forEach(function(v) { v.bc = bary(v, dir); }); - l.sort(function(a, b) { return a.bc - b.bc || a.ord - b.ord; }); + l.sort(function(a, b) { return (a.aux ? 1 : 0) - (b.aux ? 1 : 0) || a.bc - b.bc || a.ord - b.ord; }); pos(l); }; for (var it = 0; it < 6; it++) { @@ -417,6 +439,22 @@ settle(r, [ 'up', 'down' ]); } + // the lane under the rest + var mainMax = -Infinity, auxMin = Infinity, lane = null; + layers.forEach(function(l) { + l.forEach(function(v) { + if (v.aux) + auxMin = Math.min(auxMin, v.y); + else + mainMax = Math.max(mainMax, v.y + v.h); + }); + }); + if (auxMin < Infinity) { + var shift = mainMax + LANE_GAP - auxMin; + layers.forEach(function(l) { l.forEach(function(v) { if (v.aux) v.y += shift; }); }); + lane = mainMax + LANE_GAP / 2; + } + var minY = Infinity, maxY = -Infinity, maxX = 0; layers.forEach(function(l) { l.forEach(function(v) { @@ -426,9 +464,11 @@ }); }); layers.forEach(function(l) { l.forEach(function(v) { v.y -= minY; }); }); + if (lane != null) + lane -= minY; m.list.forEach(function(n) { var v = info[n.id]; - out[n.id] = { x: v.x, y: v.y, w: v.w, h: v.h, rank: v.rank }; + out[n.id] = { x: v.x, y: v.y, w: v.w, h: v.h, rank: v.rank, aux: v.aux }; }); // edges: through the dummies; the ends spread over the node's side by the far end's y @@ -459,7 +499,7 @@ return { x: i == 0 ? p.x + p.w : p.x, y: p.y + (i == 0 || last ? p.dy || 0 : 0) }; }); }); - return { nodes: out, edges: edges, width: maxX, height: maxY - minY, ranks: maxRank + 1 }; + return { nodes: out, edges: edges, width: maxX, height: maxY - minY, ranks: maxRank + 1, lane: lane }; } // --- live state (mihomo API) ------------------------------------------------- @@ -524,9 +564,9 @@ var f = find(name, user); if (f && f.v) return 'v:' + f.v; - return 'b:' + name + '@' + user; + return 'b:' + name; }; - // from a node on: the dialer-proxy chain and the groups' current choice + // from a node on: the dialer-proxy chain (or direct) and the groups' current choice var tail = function(id, path) { for (var guard = 0; guard < 24; guard++) { var n = m.nodes[id], next = null; @@ -534,12 +574,8 @@ break; if (n.kind == 'group' && L.now[id] != null) next = idOf(L.now[id], id); - else if (n.kind == 'proxy' || n.kind == 'provider') { - var d = n.kind == 'proxy' ? n.data.def['dialer-proxy'] - : n.data.def.override && n.data.def.override['dialer-proxy']; - if (d) - next = m.ref(d, id); - } + else if (n.kind == 'proxy' || n.kind == 'provider') + next = m.dialerOf[id] || null; if (!next || path.indexOf(next) >= 0) break; path.push(next); @@ -562,8 +598,9 @@ var rate = dt > 0 && prevBytes[c.id] != null ? Math.max(0, b - prevBytes[c.id]) / dt : 0; var path = [ rid ], user = rid; (c.chains || []).slice().reverse().forEach(function(name) { + // only along the graph's edges: a rule to DIRECT ends at the rule var id = idOf(name, user); - if (m.nodes[id] && path[path.length - 1] != id) + if (edgeIndex[path[path.length - 1] + '\n' + id] != null) path.push(id); user = id; }); @@ -621,13 +658,16 @@ '.mkg .e.dialer{stroke:var(--dial);stroke-dasharray:6 3;stroke-opacity:.8}' + '.mkg .e.fetch{stroke:var(--fetch);stroke-dasharray:2 4;stroke-width:1.5;stroke-opacity:.8}' + '.mkg .e.file{stroke:var(--fetch);stroke-dasharray:1 3;stroke-opacity:.6}' + - '.mkg .lbl{fill:var(--mute);font-size:10px;paint-order:stroke;stroke:var(--bg);stroke-width:3px;stroke-linejoin:round}' + + '.mkg .e.wan{stroke-dasharray:3 3;stroke-opacity:.45}' + + '.mkg .lane{stroke:var(--rule-b);stroke-dasharray:4 4}.mkg .lane-t{fill:var(--mute);font-size:11px}' + + '.mkg .lbl{fill:var(--mute);font-size:10px;paint-order:stroke;stroke:var(--bg);stroke-width:3px;stroke-linejoin:round;opacity:0}' + + '.mkg .focus .lbl.hl{opacity:1}' + '.mkg .live .e.off{stroke-opacity:.15}' + '.mkg .e.now{stroke:var(--now);stroke-opacity:.95;stroke-width:2}' + '.mkg .e.flow{stroke:var(--flow);stroke-opacity:.95;stroke-dasharray:8 6;animation:mkg-flow 1s linear infinite}' + '@keyframes mkg-flow{to{stroke-dashoffset:-14}}' + '@media (prefers-reduced-motion:reduce){.mkg .e.flow{animation:none}}' + - '.mkg .focus .n:not(.hl){opacity:.25}.mkg .focus .e:not(.hl),.mkg .focus .lbl:not(.hl){opacity:.08}' + + '.mkg .focus .n:not(.hl){opacity:.25}.mkg .focus .e:not(.hl){opacity:.08}' + '.mkg .focus .e.hl{stroke-opacity:1;stroke-width:2.2}' + '.mkg .n.sel rect{stroke-width:3}' + '.mkg-info{margin-top:8px;padding:8px 10px;border:1px solid var(--rule-b);border-radius:6px;background:var(--bg);display:none}' + @@ -638,6 +678,9 @@ '.mkg-info ul{margin:2px 0;padding-left:18px;max-height:14em;overflow:auto}' + '.mkg-warn{color:var(--miss-b);font-size:11px}' + '.mkg-zoom{position:absolute;right:8px;bottom:8px;display:flex;gap:4px}' + + '.mkg.mkg-max{position:fixed;inset:0;z-index:10000;background:var(--bg);padding:10px 12px;overflow:auto;box-sizing:border-box}' + + '.mkg:fullscreen{background:var(--bg);padding:10px 12px;overflow:auto;box-sizing:border-box}' + + '.mkg.mkg-max .mkg-stage,.mkg:fullscreen .mkg-stage{height:calc(100vh - 96px)!important}' + '.mkg-zoom button{min-width:28px}'; function el(tag, attrs, kids) { @@ -692,6 +735,7 @@ el('span', {}, [ el('i', { style: 'background:var(--prov);border-color:var(--prov-b)' }), 'подписки' ]), el('span', {}, [ el('i', { style: 'background:var(--proxy);border-color:var(--proxy-b)' }), 'серверы' ]), el('span', {}, [ el('s', { style: 'border-color:var(--dial);border-top-style:dashed' }), 'dialer-proxy' ]), + el('span', {}, [ el('s', { style: 'border-color:var(--line);border-top-style:dashed' }), 'к серверу напрямую' ]), el('span', {}, [ el('s', { style: 'border-color:var(--fetch);border-top-style:dotted' }), 'качается через' ]), el('span', {}, [ el('s', { style: 'border-color:var(--now)' }), 'выбрано сейчас' ]), el('span', {}, [ el('s', { style: 'border-color:var(--flow);border-top-style:dashed' }), 'трафик' ]) @@ -723,22 +767,43 @@ var m = null, lay = null, L = null, nodeEls = {}, edgeEls = [], selected = null; var view = { x: 0, y: 0, k: 1 }; var apply = function() { world.setAttribute('transform', 'translate(' + view.x + ',' + view.y + ') scale(' + view.k + ')'); }; + var maxed = function() { return document.fullscreenElement == root || root.classList.contains('mkg-max'); }; var fit = function() { if (!lay) return; - // as wide as the box, at most 72% of the window high; the box no taller than the graph - var W = stage.clientWidth || 800, H = Math.max(360, (window.innerHeight || 800) * 0.72), pad = 16; + // full screen: the whole window; else at most 72% of it high, the box no taller than the graph + var W = stage.clientWidth || 800, pad = 16; + var H = maxed() ? stage.clientHeight : Math.max(360, (window.innerHeight || 800) * 0.72); view.k = Math.min(1.2, (W - pad * 2) / Math.max(lay.width, 1), (H - pad * 2) / Math.max(lay.height, 1)); view.k = Math.max(view.k, 0.35); - stage.style.height = Math.round(Math.min(H, Math.max(360, lay.height * view.k + pad * 2 + 40))) + 'px'; + if (!maxed()) + stage.style.height = Math.round(Math.min(H, Math.max(360, lay.height * view.k + pad * 2 + 40))) + 'px'; view.x = pad; view.y = pad; apply(); }; + // the Fullscreen API, or a fixed overlay where there is none (iPhone Safari) + var full = function() { + if (maxed()) { + if (document.fullscreenElement) + document.exitFullscreen(); + root.classList.remove('mkg-max'); + } else if (root.requestFullscreen) + root.requestFullscreen().catch(function() { root.classList.add('mkg-max'); }); + else + root.classList.add('mkg-max'); + window.setTimeout(fit, 120); + }; + document.addEventListener('fullscreenchange', function() { window.setTimeout(fit, 120); }); + document.addEventListener('keydown', function(ev) { + if (ev.key == 'Escape' && root.classList.contains('mkg-max')) + full(); + }); stage.appendChild(el('div', { 'class': 'mkg-zoom' }, [ el('button', { 'class': 'btn cbi-button', title: 'крупнее', onclick: function() { zoomAt(1.25); } }, [ '+' ]), el('button', { 'class': 'btn cbi-button', title: 'мельче', onclick: function() { zoomAt(0.8); } }, [ '−' ]), - el('button', { 'class': 'btn cbi-button', title: 'весь граф', onclick: fit }, [ '⤢' ]) + el('button', { 'class': 'btn cbi-button', title: 'весь граф', onclick: fit }, [ '⤢' ]), + el('button', { 'class': 'btn cbi-button', title: 'на весь экран (Esc — выйти)', onclick: function() { full(); } }, [ '⛶' ]) ])); var zoomAt = function(f, cx, cy) { if (cx == null) { @@ -960,6 +1025,12 @@ nodeEls[n.id] = g; gn.appendChild(g); }); + if (lay.lane != null) + world.appendChild(el('g', {}, [ + el('path', { 'class': 'lane', d: 'M0,' + lay.lane + 'H' + lay.width }), + el('text', { 'class': 'lane-t', x: 0, y: lay.lane + 16, + text: 'служебное — правила сюда не ведут: через что качаются подписки' }) + ])); world.appendChild(ge); world.appendChild(gl); world.appendChild(gn); diff --git a/tools/test-graph.js b/tools/test-graph.js index 247a12f..5f19f33 100644 --- a/tools/test-graph.js +++ b/tools/test-graph.js @@ -33,6 +33,19 @@ for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".yaml"))) { for (let i = 1; i < c.length; i++) check(f, c[i].y >= c[i - 1].y + c[i - 1].h - 0.01, "nodes overlap in column x=" + x); } + const lastX = Math.max(...m.list.map((n) => lay.nodes[n.id].x)); + for (const n of m.list) { + const b = lay.nodes[n.id]; + if (n.exit) + check(f, b.x == lastX, n.id + " is an exit but not in the last column"); + if (b.aux) + check(f, lay.lane != null && b.y > lay.lane, n.id + " is not under the lane"); + // every proxy and subscription goes somewhere: through a dialer or directly + if ((n.kind == "proxy" && !n.exit) || n.kind == "provider") + check(f, m.dialerOf[n.id], n.id + " has no way out"); + } + if (cfg["proxy-groups"].some((g) => g.name == "BOOT-AUTO")) + check(f, lay.nodes["g:BOOT-AUTO"].aux, "BOOT-AUTO is not in the lane"); for (const le of lay.edges) if (le.pts) for (let i = 1; i < le.pts.length; i++)