app.js 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. /* =====================================================================
  2. L2 Physical Topology — display-only interactive map.
  3. Groups switches into frames (COBCO outer → workshop/DataCenter/Core),
  4. colours links by speed, nodes by latency & alarm, supports dark mode,
  5. terminal show / only-offline, live + historical snapshots, MAC/IP search.
  6. ===================================================================== */
  7. (function () {
  8. 'use strict';
  9. var CFG = window.L2_CFG || {};
  10. var T = window.L2_I18N || {};
  11. var META = window.L2_META || {};
  12. var SNAP = window.L2SNAP || null;
  13. var colors = CFG.colors || {100:'#F39C12',1000:'#2ECC71',10000:'#3498DB',20000:'#9B59B6',unknown:'#E74C3C',down:'#C0392B'};
  14. var LATW = (CFG.latency_warn != null) ? +CFG.latency_warn : 3;
  15. var LATB = (CFG.latency_bad != null) ? +CFG.latency_bad : 5;
  16. var TIER_BG = {core:'#1F4E78', dist:'#2E75B6', access:'#548235'};
  17. var TIER_BG_DARK = {core:'#1B4A72', dist:'#2A5E93', access:'#3E6B2E'};
  18. var SEV_COLORS = ['#97AAB3','#7499FF','#FFC859','#FFA059','#E97659','#E45959'];
  19. var NODE_W = 156, NODE_H = 50, GX = 26, GY = 18, PADX = 20, PADY = 42;
  20. var DGAP_X = 18, DGAP_Y = 26;
  21. var GROUP_GAP_X = 46, GROUP_GAP_Y = 48, MAXW = 2800;
  22. // overview ("全景") tiles
  23. var TILE_W = 232, TILE_H = 116, TILE_GAP_X = 24, TILE_GAP_Y = 22;
  24. var cy = null;
  25. var dark = false;
  26. var showTerm = false;
  27. var onlyOff = false;
  28. var pinnedTerm = null;
  29. var paused = false;
  30. var countdown = 0;
  31. var timer = null;
  32. var lastSnap = null;
  33. var viewGroup = null; // direct-link focus group, never hides the full chart
  34. var detailNet = null; // null/auto, 'SURVE' or 'OFFICE' inside a workshop
  35. var focusGroupLabel = null; // ?g= target, zoomed after the full chart is built
  36. var pathParent = {}; // child -> parent chain for hover highlighting
  37. var lockedPath = null; // switch id whose path is locked by click
  38. function el(id) { return document.getElementById(id); }
  39. function t(k, d) { return (T[k] != null) ? T[k] : (d != null ? d : k); }
  40. /* ---------------- name parsing / grouping ---------------- */
  41. function parseName(name) {
  42. var r = {workshop:'', floor:'', cab:'', u:'', area:'', role:'', ip:''};
  43. if (!name) return r;
  44. var toks = String(name).split('-');
  45. for (var i = 0; i < toks.length; i++) {
  46. var tk = toks[i];
  47. if (/^\d{1,3}(\.\d{1,3}){3}$/.test(tk)) { r.ip = tk; continue; }
  48. if (!r.workshop && /^\d{4}[A-Za-z]?$/.test(tk)) { r.workshop = tk; continue; }
  49. if (!r.floor) {
  50. var fm = /^(GRD|\d{1,2}F)([A-Z])?(\d+)?$/i.exec(tk);
  51. if (fm) { r.floor = fm[1].toUpperCase(); r.cab = fm[2] || ''; r.u = fm[3] || ''; continue; }
  52. }
  53. if (r.floor && !r.u && /^\d{1,3}$/.test(tk)) { r.u = tk; continue; }
  54. if (!r.area && /^(OFFICE|SURVE|GRDA|DC|IDC|LAB|PROD)$/i.test(tk)) { r.area = tk.toUpperCase(); continue; }
  55. if (!r.role && /^(Dist|Access|Core)$/i.test(tk)) { r.role = tk; }
  56. }
  57. return r;
  58. }
  59. function labelFor(n) {
  60. var p = parseName(n.name);
  61. var l1 = [];
  62. if (p.workshop) l1.push(p.workshop);
  63. if (p.area) l1.push(p.area);
  64. if (!l1.length) {
  65. l1.push((n.name || '').split('-')[0] || n.ip);
  66. }
  67. var l2 = [];
  68. if (p.floor) { var loc = p.floor + 'F' + (p.cab || '') + (p.u ? '-' + p.u + 'U' : ''); l1.push(loc); }
  69. if (p.role) l2.push(p.role);
  70. l2.push(n.ip);
  71. return l1.join(' · ') + '\n' + l2.join(' · ');
  72. }
  73. function detailLabel(n) {
  74. var s = labelFor(n);
  75. if (viewGroup) {
  76. var p = viewGroup + ' · ';
  77. if (s.indexOf(p) === 0) s = s.substring(p.length);
  78. }
  79. return s;
  80. }
  81. function rowLabel(n) {
  82. var s = String((n && n.name) || (n && n.ip) || '');
  83. s = s.replace(/^COBCO-/i, '');
  84. if (viewGroup) {
  85. try { s = s.replace(new RegExp('^' + viewGroup + '-', 'i'), ''); } catch (e) {}
  86. }
  87. return s;
  88. }
  89. function rootLabel(n) {
  90. var s = rowLabel(n);
  91. var m = /^(.+?)-(SURVE|OFFICE|OTHER)-(Dist|Access)-(.+)$/i.exec(s);
  92. if (m) return m[2].toUpperCase() + ' · ' + m[1] + '\n' + m[3] + ' · ' + m[4];
  93. return s;
  94. }
  95. function expandLabel(tpl, m) {
  96. return String(tpl).replace(/\$(\d)/g, function (_, d) { return m && m[+d] != null ? m[+d] : ''; });
  97. }
  98. function groupOf(n) {
  99. var name = n.name || n.ip || '';
  100. var rules = CFG.group_rules || [];
  101. for (var i = 0; i < rules.length; i++) {
  102. var r = rules[i];
  103. if (r.match === 'regex') {
  104. var re;
  105. try { re = new RegExp(r.pattern); } catch (e) { continue; }
  106. var m = re.exec(name);
  107. if (m) return {label: expandLabel(r.label, m) || (CFG.other_label || 'Other'), big: !!r.big};
  108. } else {
  109. if (name.toLowerCase().indexOf(String(r.pattern).toLowerCase()) >= 0) return {label: r.label || (CFG.other_label || 'Other'), big: !!r.big};
  110. }
  111. }
  112. return {label: CFG.other_label || 'Other', big: false};
  113. }
  114. /* ---------------- overview layout (workshop tiles) ---------------- */
  115. function groupStats(snap) {
  116. var map = {};
  117. var nodeById = {};
  118. (snap.nodes || []).forEach(function (n) {
  119. nodeById[n.id] = n;
  120. var g = groupOf(n);
  121. var s = map[g.label] || (map[g.label] = {label: g.label, big: g.big, nodes: [], alarms: 0, offline: 0, maxsev: -1, latmax: 0, up: 0});
  122. s.nodes.push(n);
  123. s.offline += (+n.term_offline || 0);
  124. if (n.alarms && n.alarms.length) {
  125. s.alarms += n.alarms.length;
  126. var sev = (n.maxsev != null && +n.maxsev >= 0) ? +n.maxsev : -1;
  127. n.alarms.forEach(function (a) { if (a && a.sev != null && +a.sev > sev) sev = +a.sev; });
  128. if (sev > s.maxsev) s.maxsev = sev;
  129. }
  130. if (n.latency_ms != null && +n.latency_ms > s.latmax) s.latmax = +n.latency_ms;
  131. });
  132. (snap.edges || []).forEach(function (e) {
  133. var a = nodeById[e.source], b = nodeById[e.target];
  134. if (!a || !b) return;
  135. var ga = groupOf(a), gb = groupOf(b);
  136. if (ga.label === gb.label) return;
  137. // count links that leave this workshop towards a core switch
  138. if ((/core/i.test(a.tier || '') || /core/i.test(a.name || '')) && map[gb.label]) map[gb.label].up++;
  139. if ((/core/i.test(b.tier || '') || /core/i.test(b.name || '')) && map[ga.label]) map[ga.label].up++;
  140. });
  141. return map;
  142. }
  143. function groupRank(l) {
  144. if (/core/i.test(l)) return 0;
  145. if (/data\s*center/i.test(l)) return 1;
  146. var m = /^(\d{4})([A-Za-z]?)$/.exec(l);
  147. if (m) return 1000 + parseInt(m[1], 10) * 40 + (m[2] ? m[2].toUpperCase().charCodeAt(0) - 64 : 0);
  148. return 5000;
  149. }
  150. function computeOverview(snap) {
  151. var stats = groupStats(snap);
  152. var labels = Object.keys(stats).sort(function (a, b) { return groupRank(a) - groupRank(b); });
  153. var special = labels.filter(function (l) { return groupRank(l) < 1000; });
  154. var others = labels.filter(function (l) { return groupRank(l) >= 1000; });
  155. var COLS = Math.max(4, Math.min(7, Math.ceil(Math.sqrt(Math.max(1, others.length)))));
  156. var gridW = COLS * TILE_W + (COLS - 1) * TILE_GAP_X;
  157. var pos = {}, tiles = [], y = 0;
  158. if (special.length) {
  159. var sW = special.length * TILE_W + (special.length - 1) * TILE_GAP_X;
  160. var sx = Math.max(0, (gridW - sW) / 2);
  161. special.forEach(function (l) {
  162. tiles.push({label: l, x: sx, y: y, w: TILE_W, h: TILE_H});
  163. pos[l] = {x: sx + TILE_W / 2, y: y + TILE_H / 2};
  164. sx += TILE_W + TILE_GAP_X;
  165. });
  166. y += TILE_H + 46;
  167. }
  168. var maxX = gridW, maxY = y;
  169. for (var i = 0; i < others.length; i += COLS) {
  170. var row = others.slice(i, i + COLS);
  171. var rW = row.length * TILE_W + (row.length - 1) * TILE_GAP_X;
  172. var rx = Math.max(0, (gridW - rW) / 2);
  173. row.forEach(function (l, j) {
  174. tiles.push({label: l, x: rx + j * (TILE_W + TILE_GAP_X), y: y, w: TILE_W, h: TILE_H});
  175. pos[l] = {x: rx + j * (TILE_W + TILE_GAP_X) + TILE_W / 2, y: y + TILE_H / 2};
  176. });
  177. y += TILE_H + TILE_GAP_Y;
  178. maxY = y - TILE_GAP_Y;
  179. maxX = Math.max(maxX, rx + rW);
  180. }
  181. var root = {x: -34, y: -64, w: maxX + 68, h: maxY + 64 + 40};
  182. root.cx = root.x + root.w / 2; root.cy = root.y + root.h / 2;
  183. return {stats: stats, labels: labels, pos: pos, tiles: tiles, root: root};
  184. }
  185. function aggregateEdges(snap) {
  186. var gid = {};
  187. (snap.nodes || []).forEach(function (n) { gid[n.id] = groupOf(n).label; });
  188. var pairs = {};
  189. (snap.edges || []).forEach(function (e) {
  190. var a = gid[e.source], b = gid[e.target];
  191. if (!a || !b || a === b) return;
  192. var k = (a < b) ? (a + '\u0001' + b) : (b + '\u0001' + a);
  193. var p = pairs[k] || (pairs[k] = {a: a, b: b, count: 0, speed: 0, down: false});
  194. p.count++;
  195. if ((parseFloat(e.speed) || 0) > p.speed) p.speed = parseFloat(e.speed) || 0;
  196. if (e.state && e.state !== 'up') p.down = true;
  197. });
  198. return Object.keys(pairs).map(function (k) { return pairs[k]; });
  199. }
  200. /* ---------------- detail layout (one workshop, left-to-right tree) ---------------- */
  201. function floorInfo(n) {
  202. var toks = String((n && n.name) || '').split('-');
  203. for (var i = 0; i < toks.length; i++) {
  204. var tk = toks[i];
  205. var bm = /^B(\d+)$/i.exec(tk);
  206. if (bm) { var bn = parseInt(bm[1], 10); return {key: 'B' + bn, label: 'B' + bn, rank: -200 + bn}; }
  207. if (/^GRD/i.test(tk)) return {key: 'GRD', label: 'GRD', rank: -100};
  208. var fm = /^(\d+(?:\.\d+)?)F/i.exec(tk);
  209. if (fm) {
  210. var num = parseFloat(fm[1]);
  211. var txt = (num % 1 ? num.toFixed(1) : String(num)) + 'F';
  212. return {key: txt, label: txt, rank: num * 10};
  213. }
  214. var cm = /^(\d)([A-Z])(\w+)$/i.exec(tk);
  215. if (cm) {
  216. var n2 = parseInt(cm[1], 10);
  217. return {key: n2 + 'F', label: n2 + 'F', rank: n2 * 10};
  218. }
  219. }
  220. return {key: 'NA', label: t('l2.floor_na', 'Other'), rank: -500};
  221. }
  222. function baseNetworkOf(n) {
  223. var s = String((n && n.name) || '').toUpperCase();
  224. if (s.indexOf('SURVE') >= 0) return 'SURVE';
  225. if (s.indexOf('OFFICE') >= 0) return 'OFFICE';
  226. var ip = String((n && n.ip) || '');
  227. if (/^10\.169\./.test(ip)) return 'SURVE';
  228. if (/^10\.160\./.test(ip)) return 'OFFICE';
  229. return 'OTHER';
  230. }
  231. function networkOf(n) { return baseNetworkOf(n); }
  232. function networkLabel(key) {
  233. if (key === 'SURVE') return t('l2.net_surve', 'SURVE 监控网');
  234. if (key === 'OFFICE') return t('l2.net_office', 'OFFICE 办公网');
  235. return t('l2.net_other', '其他网络');
  236. }
  237. function computeDetail(snap, label) {
  238. var all = snap.nodes || [];
  239. var byId = {}, groupNodes = [];
  240. all.forEach(function (n) { byId[n.id] = n; if (groupOf(n).label === label) groupNodes.push(n); });
  241. // Split one workshop by physical network first: office and surveillance never mix.
  242. var gids = {}, rawAdj = {};
  243. groupNodes.forEach(function (n) { gids[n.id] = true; rawAdj[n.id] = []; });
  244. (snap.edges || []).forEach(function (e) {
  245. if (gids[e.source] && gids[e.target]) { rawAdj[e.source].push(e.target); rawAdj[e.target].push(e.source); }
  246. });
  247. var netMap = {};
  248. groupNodes.forEach(function (n) { netMap[n.id] = baseNetworkOf(n); });
  249. // Unlabelled access switches inherit the network of the distribution they hang from.
  250. for (var pass = 0; pass < 4; pass++) {
  251. groupNodes.forEach(function (n) {
  252. if (netMap[n.id] !== 'OTHER') return;
  253. var votes = {};
  254. rawAdj[n.id].forEach(function (id) {
  255. var k = netMap[id];
  256. if (k && k !== 'OTHER') votes[k] = (votes[k] || 0) + 1;
  257. });
  258. var best = null, bestN = 0;
  259. Object.keys(votes).forEach(function (k) { if (votes[k] > bestN) { best = k; bestN = votes[k]; } });
  260. if (best) netMap[n.id] = best;
  261. });
  262. }
  263. var counts = {}, nets = [];
  264. groupNodes.forEach(function (n) {
  265. var k = netMap[n.id];
  266. if (!counts[k]) { counts[k] = 0; nets.push(k); }
  267. counts[k]++;
  268. });
  269. nets.sort(function (a, b) {
  270. if (a === 'SURVE') return -1;
  271. if (b === 'SURVE') return 1;
  272. if (a === 'OFFICE') return -1;
  273. if (b === 'OFFICE') return 1;
  274. return counts[b] - counts[a];
  275. });
  276. var activeNet = (detailNet && counts[detailNet]) ? detailNet : (nets.length ? nets[0] : 'OTHER');
  277. var nodes = groupNodes.filter(function (n) { return netMap[n.id] === activeNet; });
  278. var ids = {};
  279. nodes.forEach(function (n) { ids[n.id] = true; });
  280. var internal = [], external = [];
  281. (snap.edges || []).forEach(function (e) {
  282. var a = ids[e.source], b = ids[e.target];
  283. if (a && b) internal.push(e);
  284. else if (a || b) external.push(e);
  285. });
  286. var adj = {};
  287. nodes.forEach(function (n) { adj[n.id] = []; });
  288. internal.forEach(function (e) { adj[e.source].push(e.target); adj[e.target].push(e.source); });
  289. // Distribution switches are the left-hand roots of the workshop tree.
  290. var dists = nodes.filter(function (n) { return /dist/i.test(n.tier || '') && /dist/i.test(n.name || ''); })
  291. .sort(function (a, b) { return (adj[b.id].length - adj[a.id].length) || String(a.name).localeCompare(String(b.name)); });
  292. if (!dists.length) {
  293. var cand = nodes.slice().sort(function (a, b) { return adj[b.id].length - adj[a.id].length; })[0];
  294. if (cand) dists = [cand];
  295. }
  296. // One physical root per network tab; peer/redundant distribution switches are listed below it.
  297. if (dists.length > 1) dists = [dists[0]];
  298. // Group all non-distribution switches into floor buckets (GRD lowest, then 1F/2F/3F...).
  299. var floorMap = {};
  300. nodes.forEach(function (n) {
  301. if (dists.indexOf(n) >= 0) return;
  302. if (/core/i.test(n.tier || '')) return;
  303. var fi = floorInfo(n);
  304. var f = floorMap[fi.key] || (floorMap[fi.key] = {key: fi.key, label: fi.label, rank: fi.rank, nodes: []});
  305. f.nodes.push(n);
  306. });
  307. var floors = Object.keys(floorMap).map(function (k) { return floorMap[k]; });
  308. floors.forEach(function (f) {
  309. f.nodes.sort(function (a, b) {
  310. var pa = parseName(a.name), pb = parseName(b.name);
  311. var ca = (pa.cab || '') + (pa.u || ''), cb = (pb.cab || '') + (pb.u || '');
  312. if (ca !== cb) return ca.localeCompare(cb);
  313. return String(a.name).localeCompare(String(b.name));
  314. });
  315. });
  316. // Highest floor at the top, GRD at the bottom.
  317. floors.sort(function (a, b) { return b.rank - a.rank; });
  318. var WORK_L = 300, FLOOR_X = 520, DIST_FRAME_W = 190, TOP_OFF = 34;
  319. var ROW_W = 380, ROW_H = 24, ROW_GAP = 8, FLOOR_HEAD = 28, FLOOR_GAP = 12;
  320. var floorW = ROW_W + PADX * 2 + 110;
  321. floors.forEach(function (f) {
  322. f.cols = 1;
  323. f.rows = f.nodes.length;
  324. f.innerW = ROW_W;
  325. f.h = FLOOR_HEAD + f.rows * ROW_H + Math.max(0, f.rows - 1) * ROW_GAP + 10;
  326. });
  327. var workRight = FLOOR_X + floorW + 14;
  328. var workW = workRight - WORK_L;
  329. var pos = {}, top = 44 + TOP_OFF;
  330. floors.forEach(function (f) {
  331. f.frame = {x: FLOOR_X, y: top, w: floorW, h: f.h};
  332. f.nodes.forEach(function (n, i) {
  333. pos[n.id] = {
  334. x: FLOOR_X + PADX + ROW_W / 2,
  335. y: top + FLOOR_HEAD + i * (ROW_H + ROW_GAP) + ROW_H / 2
  336. };
  337. });
  338. top += f.h + FLOOR_GAP;
  339. });
  340. var workH = Math.max(220, top + 6);
  341. var distFrame = dists.length ? {x: WORK_L + 8, y: 44 + TOP_OFF, w: DIST_FRAME_W, h: workH - (44 + TOP_OFF) - 14} : null;
  342. var distX = WORK_L + 8 + DIST_FRAME_W / 2;
  343. if (dists.length) {
  344. var childYs = floors.reduce(function (acc, f) {
  345. return acc.concat(f.nodes.map(function (n) { return pos[n.id] ? pos[n.id].y : 0; }));
  346. }, []);
  347. var cy = childYs.length ? (Math.min.apply(null, childYs) + Math.max.apply(null, childYs)) / 2 : distFrame.y + distFrame.h / 2;
  348. pos[dists[0].id] = {x: distX, y: cy};
  349. }
  350. var missing = nodes.filter(function (n) { return !pos[n.id]; });
  351. missing.forEach(function (n, i) {
  352. pos[n.id] = {x: distX, y: (distFrame ? distFrame.y + 30 : 80) + i * (NODE_H + 12)};
  353. });
  354. // One ghost core per external core→distribution uplink, aligned left of its distribution switch.
  355. var ghosts = [], ghostSeen = {};
  356. external.forEach(function (e) {
  357. var inside = ids[e.source] ? e.source : e.target;
  358. var outside = ids[e.source] ? e.target : e.source;
  359. if (!pos[inside] || !byId[outside]) return;
  360. // Only a real core uplink gets a ghost; other cross-group edges are not drawn as cores.
  361. if (!/core/i.test(byId[outside].tier || '') && !/core/i.test(byId[outside].name || '')) return;
  362. var key = outside + '|' + inside;
  363. if (ghostSeen[key]) return;
  364. var g = {id: 'gh_' + outside + '_' + inside, to: inside, node: byId[outside], speed: e.speed, state: e.state};
  365. ghostSeen[key] = g;
  366. ghosts.push(g);
  367. });
  368. var ghostAt = {};
  369. ghosts.forEach(function (g) {
  370. var base = pos[g.to];
  371. var k = ghostAt[g.to] || 0;
  372. ghostAt[g.to] = k + 1;
  373. g.x = 92;
  374. g.y = base.y + (k ? (k % 2 ? 1 : -1) * 46 * Math.ceil(k / 2) : 0);
  375. });
  376. // Root each tree at the distribution switch; remember every child's parent for path highlighting.
  377. var parentOf = {}, ghostOfDist = {};
  378. ghosts.forEach(function (g) { if (!ghostOfDist[g.to]) ghostOfDist[g.to] = g.id; });
  379. var seen = {};
  380. dists.forEach(function (d) {
  381. if (seen[d.id]) return;
  382. seen[d.id] = true;
  383. parentOf[d.id] = ghostOfDist[d.id] || null;
  384. var queue = [d.id];
  385. while (queue.length) {
  386. var cur = queue.shift();
  387. adj[cur].forEach(function (nb) {
  388. if (seen[nb]) return;
  389. seen[nb] = true;
  390. parentOf[nb] = cur;
  391. queue.push(nb);
  392. });
  393. }
  394. });
  395. nodes.forEach(function (n) { if (!seen[n.id]) seen[n.id] = true; });
  396. var workshop = {x: WORK_L, y: 0, w: workW, h: workH, label: label + ' · ' + networkLabel(activeNet) + ' · ' + nodes.length + ' ' + t('l2.unit_sw', 'sw')};
  397. var distFrameFull = distFrame ? {
  398. x: distFrame.x, y: distFrame.y, w: distFrame.w, h: distFrame.h,
  399. label: t('l2.dist', 'Distribution') + ' · ' + dists.length
  400. } : null;
  401. floors.forEach(function (f) {
  402. f.frame.label = f.label + ' · ' + f.nodes.length + ' ' + t('l2.unit_sw', 'sw');
  403. });
  404. var root = {x: -20, y: -48, w: workRight + 40, h: workH + 80};
  405. root.cx = root.x + root.w / 2; root.cy = root.y + root.h / 2;
  406. return {
  407. nodes: nodes, byId: byId, pos: pos, ghosts: ghosts, parentOf: parentOf,
  408. dists: dists, floors: floors, frames: {workshop: workshop, dist: distFrameFull},
  409. root: root, totalW: workRight, ids: ids, internal: internal,
  410. nets: nets.map(function (k) { return {key: k, count: counts[k]}; }), activeNet: activeNet, totalNodes: groupNodes.length
  411. };
  412. }
  413. /* ---------------- one-chart layout: fixed columns by tier ----------------
  414. Left to right: physical core → each network's main switch → every
  415. workshop distribution switch → access switches. A workshop frame spans
  416. the distribution + access columns; each floor is a small frame inside it.
  417. Same workshop on two networks is always two separate frames. */
  418. var CORE_X = 130, MAIN_X = 430, DIST_X = 790, ACCESS_X = 1300;
  419. var CORE_W = 200, MAIN_W = 300, NODE_W3 = 300;
  420. var WORK_LEFT = 610, WORK_RIGHT = 1530;
  421. var FLOOR_LEFT = 1130, FLOOR_RIGHT = 1525;
  422. var CHART_W = 1560;
  423. var SEC_HEAD = 46, CORE_ROW = 92, WORK_TOP = 148;
  424. var ROW_H = 24, ROW_GAP = 8, WS_GAP = 20, SEC_GAP = 40;
  425. var FLOOR_GAP = 18;
  426. function makeNetworks() {
  427. var raw = CFG.networks;
  428. if (!raw || !raw.length) {
  429. raw = [
  430. {key: 'SURVE', label: t('l2.net_surve', 'SURVE 监控网'), keywords: ['SURVE', '10.169.'], color: '#2E75B6'},
  431. {key: 'OFFICE', label: t('l2.net_office', 'OFFICE 办公网'), keywords: ['OFFICE', '10.160.'], color: '#548235'}
  432. ];
  433. }
  434. return raw.map(function (n, i) {
  435. var kws = n.keywords;
  436. if (!(kws instanceof Array)) kws = String(kws || '').split(/[,,;;\s]+/);
  437. return {
  438. key: String(n.key || ('NET' + i)).trim().toUpperCase(),
  439. label: String(n.label || n.key || ('NET' + i)),
  440. keywords: kws.map(function (s) { return String(s).trim(); }).filter(Boolean),
  441. color: /^#[0-9a-fA-F]{6}$/.test(String(n.color || '')) ? n.color : '#607D8B'
  442. };
  443. });
  444. }
  445. var NETWORKS = makeNetworks();
  446. function netLabel(key) {
  447. for (var i = 0; i < NETWORKS.length; i++) if (NETWORKS[i].key === key) return NETWORKS[i].label;
  448. return key === 'OTHER' ? t('l2.net_other', '其他网络') : String(key || '');
  449. }
  450. function netColor(key) {
  451. for (var i = 0; i < NETWORKS.length; i++) if (NETWORKS[i].key === key) return NETWORKS[i].color;
  452. return '#607D8B';
  453. }
  454. function rawNetOf(n) {
  455. var hay = (String((n && n.name) || '') + ' ' + String((n && n.ip) || '')).toUpperCase();
  456. for (var i = 0; i < NETWORKS.length; i++) {
  457. for (var j = 0; j < NETWORKS[i].keywords.length; j++) {
  458. if (hay.indexOf(String(NETWORKS[i].keywords[j]).toUpperCase()) >= 0) return NETWORKS[i].key;
  459. }
  460. }
  461. return 'OTHER';
  462. }
  463. // Core/root switch rules are configured from the L2 tab, one row per core.
  464. // Multiple cores in the same network are supported and all of them are
  465. // placed in the left-most core column.
  466. function coreRules() {
  467. var r = CFG.core_rules;
  468. return (r instanceof Array) ? r : [];
  469. }
  470. function coreRuleHit(rule, n) {
  471. var pattern = String(rule.pattern || '');
  472. if (!pattern) return false;
  473. var net = String(rule.net || '').toUpperCase();
  474. if (net) {
  475. var raw = rawNetOf(n);
  476. // A core with no recognisable network keyword may still be assigned by
  477. // the rule; a switch already known to belong to another network must
  478. // not be stolen by a broad pattern.
  479. if (raw !== 'OTHER' && raw !== net) return false;
  480. }
  481. var hay = String((n && n.name) || '') + ' ' + String((n && n.ip) || '');
  482. if (String(rule.match || 'contains') === 'regex') {
  483. try { return new RegExp(pattern, 'i').test(hay); } catch (e) { return false; }
  484. }
  485. return hay.toLowerCase().indexOf(pattern.toLowerCase()) >= 0;
  486. }
  487. function configuredCore(n) {
  488. var rules = coreRules();
  489. for (var i = 0; i < rules.length; i++) if (coreRuleHit(rules[i], n)) return true;
  490. return false;
  491. }
  492. function configuredCoreNet(n) {
  493. var rules = coreRules();
  494. for (var i = 0; i < rules.length; i++) {
  495. if (coreRuleHit(rules[i], n) && String(rules[i].net || '').trim() !== '') return String(rules[i].net).toUpperCase();
  496. }
  497. return '';
  498. }
  499. // Network is decided first by name/IP keyword, then by the rest of the
  500. // workshop, then by graph adjacency. No switch is ever shown under the
  501. // wrong upstream network.
  502. function assignNetworks(snap) {
  503. var nodes = snap.nodes || [], byId = {}, net = {}, adj = {};
  504. nodes.forEach(function (n) {
  505. byId[n.id] = n; net[n.id] = rawNetOf(n); adj[n.id] = [];
  506. var cn = configuredCoreNet(n);
  507. if (cn) net[n.id] = cn;
  508. });
  509. (snap.edges || []).forEach(function (e) {
  510. if (adj[e.source] && adj[e.target]) { adj[e.source].push(e.target); adj[e.target].push(e.source); }
  511. });
  512. var groupVote = {};
  513. nodes.forEach(function (n) {
  514. var k = groupOf(n).label, v = net[n.id];
  515. if (v && v !== 'OTHER') (groupVote[k] = groupVote[k] || {})[v] = true;
  516. });
  517. nodes.forEach(function (n) {
  518. if (net[n.id] !== 'OTHER') return;
  519. var v = groupVote[groupOf(n).label], keys = v ? Object.keys(v) : [];
  520. if (keys.length === 1) net[n.id] = keys[0];
  521. });
  522. for (var pass = 0; pass < 8; pass++) {
  523. var changed = false;
  524. nodes.forEach(function (n) {
  525. if (net[n.id] !== 'OTHER') return;
  526. var votes = {};
  527. adj[n.id].forEach(function (id) { if (net[id] && net[id] !== 'OTHER') votes[net[id]] = (votes[net[id]] || 0) + 1; });
  528. var best = null, bn = 0;
  529. Object.keys(votes).forEach(function (k) { if (votes[k] > bn) { best = k; bn = votes[k]; } });
  530. if (best) { net[n.id] = best; changed = true; }
  531. });
  532. if (!changed) break;
  533. }
  534. return net;
  535. }
  536. function roleOf(n) {
  537. var p = parseName(n.name || '');
  538. var r = String(p.role || '').toLowerCase();
  539. var tier = String(n.tier || '').toLowerCase();
  540. if (configuredCore(n)) return 'core';
  541. // Backward-compatible fallback only when the core list is absent (old
  542. // config). An explicitly empty list means the administrator wants no
  543. // configured core column.
  544. if (!(CFG.core_rules instanceof Array) && (/^core(\s|-)/i.test(String(n.name || '')) || groupOf(n).label === 'Core')) return 'core';
  545. if (tier === 'core' || r === 'core') return 'main';
  546. if (r === 'dist') return 'dist';
  547. if (r === 'access') return 'access';
  548. if (tier.indexOf('dist') === 0) return 'dist';
  549. return 'access';
  550. }
  551. function roleName(r) {
  552. if (r === 'core') return t('l2.core', '核心');
  553. if (r === 'main') return t('l2.main', '主交换');
  554. if (r === 'dist') return t('l2.dist', '汇聚');
  555. return t('l2.access', '接入');
  556. }
  557. function shortLoc(n) {
  558. var p = parseName(n.name || '');
  559. if (!p.floor) return '';
  560. return p.floor + (p.cab || '') + (p.u ? '-' + p.u : '');
  561. }
  562. function switchLabel(n, role, netKey) {
  563. var g = groupOf(n).label;
  564. if (role === 'core') return roleName('core') + ' · ' + (netKey || rawNetOf(n)) + ' · ' + (n.ip || '');
  565. if (role === 'main') return roleName('main') + ' · ' + g + ' · ' + (n.ip || '');
  566. var loc = shortLoc(n);
  567. return [g, loc, roleName(role)].filter(Boolean).join(' · ') + ' · ' + (n.ip || '');
  568. }
  569. // A workshop is the physical area served by one distribution switch, not
  570. // the four-digit prefix printed on each access switch. The same dist can
  571. // serve access switches in several rooms/buildings; they must share one
  572. // frame, otherwise their uplink line would cross unrelated frames.
  573. function workshopKeys(snap) {
  574. var byId = {}, adj = {}, keys = {};
  575. (snap.nodes || []).forEach(function (n) { byId[n.id] = n; adj[n.id] = []; });
  576. (snap.edges || []).forEach(function (e) {
  577. if (adj[e.source] && adj[e.target]) { adj[e.source].push(e.target); adj[e.target].push(e.source); }
  578. });
  579. (snap.nodes || []).forEach(function (n) {
  580. var r = roleOf(n);
  581. if (r === 'core' || r === 'main') return;
  582. if (r === 'dist') { keys[n.id] = groupOf(n).label; return; }
  583. var ds = (adj[n.id] || []).map(function (id) { return byId[id]; })
  584. .filter(function (d) { return d && roleOf(d) === 'dist'; });
  585. var same = ds.filter(function (d) { return groupOf(d).label === groupOf(n).label; });
  586. var pick = same[0] || ds[0];
  587. keys[n.id] = pick ? groupOf(pick).label : groupOf(n).label;
  588. });
  589. return keys;
  590. }
  591. function workshopList(snap, netMap, netKey, wsKeys) {
  592. var map = {}, order = [];
  593. (snap.nodes || []).forEach(function (n) {
  594. if (netMap[n.id] !== netKey) return;
  595. var r = roleOf(n);
  596. if (r === 'core' || r === 'main') return;
  597. var g = (wsKeys && wsKeys[n.id]) || groupOf(n).label;
  598. if (!map[g]) { map[g] = {key: g, label: g, extra: [], net: netKey, dists: [], access: [], all: []}; order.push(g); }
  599. map[g].all.push(n);
  600. if (r === 'dist') map[g].dists.push(n); else map[g].access.push(n);
  601. });
  602. return order.map(function (g) { return map[g]; }).filter(function (w) { return w.all.length > 0; })
  603. .map(function (w) {
  604. w.access.forEach(function (a) {
  605. var raw = groupOf(a).label;
  606. if (raw !== w.key && w.extra.indexOf(raw) < 0) w.extra.push(raw);
  607. });
  608. w.label = w.key + (w.extra.length ? ' + ' + w.extra.slice(0, 3).join('/') + (w.extra.length > 3 ? '…' : '') : '');
  609. return w;
  610. });
  611. }
  612. function layoutWorkshop(w, top) {
  613. var rowH = ROW_H + ROW_GAP + (showTerm ? 24 : 0);
  614. var floorMap = {}, floors = [];
  615. w.access.forEach(function (n) {
  616. var fi = floorInfo(n);
  617. var k = fi.key;
  618. if (!floorMap[k]) { floorMap[k] = {key: k, label: fi.label, rank: (fi.key === 'NA' ? 999 : fi.rank), nodes: [], rows: []}; floors.push(floorMap[k]); }
  619. floorMap[k].nodes.push(n);
  620. });
  621. floors.sort(function (a, b) { return a.rank - b.rank || String(a.label).localeCompare(String(b.label)); });
  622. var accessH = 0;
  623. floors.forEach(function (f) {
  624. f.nodes.sort(function (a, b) { return String(a.name).localeCompare(String(b.name)); });
  625. f.h = 24 + f.nodes.length * rowH + 8;
  626. accessH += f.h;
  627. });
  628. if (floors.length > 1) accessH += (floors.length - 1) * FLOOR_GAP;
  629. var distH = w.dists.length ? (w.dists.length * 64 + (w.dists.length - 1) * 8) : 0;
  630. var inner = Math.max(accessH, distH, 54);
  631. var h = 38 + inner + 10;
  632. w.top = top; w.h = h; w.rowH = rowH;
  633. // Floors are stacked bottom-up: GRD lowest, then 1F → 3F → 4F → 7F.
  634. var cursor = top + h - 8;
  635. floors.forEach(function (f) {
  636. cursor -= f.h;
  637. f.frame = {x: FLOOR_LEFT, y: cursor, w: FLOOR_RIGHT - FLOOR_LEFT, h: f.h};
  638. f.nodes.forEach(function (n, i) {
  639. f.rows.push({id: n.id, x: ACCESS_X, y: cursor + 22 + rowH / 2 + i * rowH});
  640. });
  641. cursor -= FLOOR_GAP;
  642. });
  643. var dstart = top + 38 + (inner - distH) / 2;
  644. w.distPos = w.dists.map(function (n, i) {
  645. return {id: n.id, x: DIST_X, y: dstart + 32 + i * 72};
  646. });
  647. w.floors = floors;
  648. w.title = w.label + ' · ' + netLabel(w.net) + ' · ' + w.all.length + ' ' + t('l2.unit_sw', '台');
  649. // A workshop without a distribution switch only needs a box around its
  650. // access column; keeping the full dist-column width would leave a large
  651. // empty rectangle and make the chart look sparse.
  652. var frameLeft = w.dists.length ? WORK_LEFT : FLOOR_LEFT - 40;
  653. w.frame = {x: frameLeft, y: top, w: WORK_RIGHT - frameLeft, h: h};
  654. return h;
  655. }
  656. function computeFull(snap) {
  657. var nodes = snap.nodes || [];
  658. var netMap = assignNetworks(snap);
  659. var sections = [], placements = [], frames = [], roleMap = {};
  660. var wsKeys = workshopKeys(snap);
  661. var y = 100;
  662. NETWORKS.forEach(function (net) {
  663. var secNodes = nodes.filter(function (n) { return netMap[n.id] === net.key; });
  664. if (!secNodes.length) return;
  665. var cores = [], main = null;
  666. secNodes.forEach(function (n) {
  667. roleMap[n.id] = roleOf(n);
  668. if (roleMap[n.id] === 'core') cores.push(n);
  669. if (roleMap[n.id] === 'main' && !main) main = n;
  670. });
  671. var ws = workshopList(snap, netMap, net.key, wsKeys);
  672. var sec = {
  673. key: net.key, label: netLabel(net.key) + ' · ' + secNodes.length + ' ' + t('l2.unit_sw', '台'),
  674. x: 10, y: y, w: CHART_W - 20, h: 0, color: netColor(net.key),
  675. core: cores[0] || null, cores: cores, main: main, workshops: ws
  676. };
  677. var cur = y + WORK_TOP;
  678. ws.forEach(function (w) {
  679. layoutWorkshop(w, cur);
  680. cur += w.h + WS_GAP;
  681. frames.push({id: 'ws_' + net.key + '_' + w.key, type: 'wsframe', x: w.frame.x, y: w.frame.y, w: w.frame.w, h: w.frame.h,
  682. label: w.title, group: w.key, net: net.key, color: net.color});
  683. w.floors.forEach(function (f, fi) {
  684. frames.push({id: 'ff_' + net.key + '_' + w.key + '_' + fi, type: 'floorframe', x: f.frame.x, y: f.frame.y,
  685. w: f.frame.w, h: f.frame.h, label: f.label + ' · ' + f.nodes.length + ' ' + t('l2.unit_sw', '台'), net: net.key, color: net.color});
  686. });
  687. w.distPos.forEach(function (p) {
  688. var n = nodes.filter(function (x) { return x.id === p.id; })[0];
  689. if (n) placements.push({node: n, role: 'dist', x: p.x, y: p.y, w: NODE_W3, h: 26, net: net.key, group: w.key, ws: net.key + '|' + w.key});
  690. });
  691. w.floors.forEach(function (f) {
  692. f.rows.forEach(function (p) {
  693. var n = nodes.filter(function (x) { return x.id === p.id; })[0];
  694. if (n) placements.push({node: n, role: 'access', x: p.x, y: p.y, w: NODE_W3, h: 26, net: net.key, group: w.key, ws: net.key + '|' + w.key});
  695. });
  696. });
  697. });
  698. sec.h = (cur - y) + 16;
  699. // The network main switch stays at the top of its tier column (its access
  700. // children sit directly under it, as in the reference chart); the core
  701. // sits lower in the column so its uplinks fan symmetrically.
  702. sec.mainY = y + SEC_HEAD + 46;
  703. sec.coreY = y + Math.max(CORE_ROW + SEC_HEAD, Math.round(sec.h * 0.55));
  704. if (cores.length) {
  705. var coreStep = 64;
  706. var coreTop = sec.coreY - ((cores.length - 1) * coreStep) / 2;
  707. cores.forEach(function (cn, ci) {
  708. placements.push({node: cn, role: 'core', x: CORE_X, y: coreTop + ci * coreStep, w: CORE_W, h: 54, net: net.key, group: 'Core'});
  709. });
  710. }
  711. if (main) placements.push({node: main, role: 'main', x: MAIN_X, y: sec.mainY, w: MAIN_W, h: 46, net: net.key, group: groupOf(main).label});
  712. sections.push(sec);
  713. y += sec.h + SEC_GAP;
  714. });
  715. var root = {x: 0, y: 0, w: CHART_W, h: y + 6};
  716. return {sections: sections, placements: placements, frames: frames, netMap: netMap, roleMap: roleMap, root: root};
  717. }
  718. // Immediate upstream parent per switch: access -> its workshop dist;
  719. // dist -> core when directly attached, otherwise the network main switch.
  720. function buildParents(snap, L) {
  721. var byId = {}, adj = {}, edgeSpeed = {};
  722. L.placements.forEach(function (p) { byId[p.node.id] = p; });
  723. (snap.nodes || []).forEach(function (n) { adj[n.id] = []; });
  724. (snap.edges || []).forEach(function (e) {
  725. if (!adj[e.source] || !adj[e.target]) return;
  726. adj[e.source].push(e.target); adj[e.target].push(e.source);
  727. edgeSpeed[e.source + '|' + e.target] = edgeSpeed[e.target + '|' + e.source] = parseFloat(e.speed) || 0;
  728. });
  729. var parent = {};
  730. Object.keys(byId).forEach(function (id) {
  731. var role = L.roleMap[id] || 'access';
  732. if (role === 'core') return;
  733. var p = byId[id], cands = (adj[id] || []).map(function (x) { return {id: x, role: L.roleMap[x] || 'access', p: byId[x]}; })
  734. .filter(function (c) { return c.p; });
  735. var want = role === 'main' ? ['core'] : (role === 'dist' ? ['core', 'main'] : ['dist', 'main', 'core']);
  736. var best = null;
  737. for (var wi = 0; wi < want.length && !best; wi++) {
  738. var list = cands.filter(function (c) {
  739. if (c.role !== want[wi]) return false;
  740. if (role === 'access' && want[wi] === 'dist' && c.p.ws && p.ws && c.p.ws !== p.ws) return false;
  741. return true;
  742. });
  743. if (list.length) {
  744. list.sort(function (a, b) { return (edgeSpeed[id + '|' + b.id] || 0) - (edgeSpeed[id + '|' + a.id] || 0); });
  745. best = list[0];
  746. }
  747. }
  748. if (best) parent[id] = best.id;
  749. });
  750. return parent;
  751. }
  752. /* ---------------- speed colour ---------------- */
  753. function speedColor(speed, state) {
  754. if (state && state !== 'up') return colors.down;
  755. var s = parseFloat(speed);
  756. if (!isFinite(s) || s <= 0) return colors.unknown;
  757. if (s <= 100) return colors['100'];
  758. if (s <= 1000) return colors['1000'];
  759. if (s <= 10000) return colors['10000'];
  760. return colors['20000'];
  761. }
  762. function speedWidth(speed) {
  763. var s = parseFloat(speed) || 0;
  764. if (s >= 20000) return 4.5;
  765. if (s >= 10000) return 3.6;
  766. if (s >= 1000) return 2.6;
  767. return 1.8;
  768. }
  769. function speedText(speed) {
  770. var s = parseFloat(speed) || 0;
  771. if (!s) return '?';
  772. if (s >= 1000) return (s / 1000) + 'G';
  773. return s + 'M';
  774. }
  775. function terminalOnline(tm) {
  776. return tm && (tm.online === true || tm.online === 1 || tm.online === '1' || tm.online === 'true');
  777. }
  778. function terminalText(tm) {
  779. return tm.mac + '\n' + speedText(tm.speed);
  780. }
  781. /* ---------------- style ---------------- */
  782. function styleFor(d) {
  783. var bg = d ? TIER_BG_DARK : TIER_BG;
  784. return [
  785. {selector: 'node', style: {
  786. 'width': 'data(w)', 'height': 'data(h)', 'shape': 'round-rectangle',
  787. 'background-color': 'data(bg)', 'border-width': 2, 'border-color': 'data(bd)',
  788. 'label': 'data(label)', 'color': d ? '#eaf1fb' : '#ffffff',
  789. 'font-size': 11.5, 'font-weight': 600, 'text-valign': 'center', 'text-halign': 'center',
  790. 'text-wrap': 'wrap', 'text-max-width': NODE_W - 16, 'padding': '2px',
  791. 'overlay-opacity': 0, 'z-index-compare': 'manual', 'z-index': 20
  792. }},
  793. {selector: 'node[type="frame"]', style: {
  794. 'background-opacity': d ? 0.05 : 0.035, 'background-color': d ? '#5b7bb0' : '#8fa6c4',
  795. 'border-width': 1.6, 'border-style': 'dashed', 'border-color': d ? '#3f5377' : '#c2ccdb',
  796. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center',
  797. 'font-size': 'data(fs)', 'font-weight': 800, 'color': d ? '#aebfd8' : '#526178',
  798. 'text-margin-y': 8, 'padding': '0px', 'events': 'no', 'z-index-compare': 'manual', 'z-index': 2
  799. }},
  800. {selector: 'node[type="netframe"]', style: {
  801. 'background-opacity': d ? 0.03 : 0.02, 'background-color': d ? '#7b91b8' : '#adc0d8',
  802. 'border-width': 3, 'border-style': 'solid', 'border-color': 'data(bd)',
  803. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center',
  804. 'font-size': 22, 'font-weight': 900, 'color': d ? '#dbe9ff' : '#29425f',
  805. 'text-margin-y': 8, 'padding': '0px', 'events': 'no',
  806. 'z-index-compare': 'manual', 'z-index': 1
  807. }},
  808. {selector: 'node[type="wsframe"]', style: {
  809. 'background-opacity': d ? 0.02 : 0.014, 'background-color': d ? '#6f8fc4' : '#8fa6c4',
  810. 'border-width': 2.2, 'border-style': 'solid', 'border-color': 'data(bd)',
  811. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center', 'text-wrap': 'none',
  812. 'font-size': 15.5, 'font-weight': 900, 'color': d ? '#d7e6ff' : '#2f4560',
  813. 'text-margin-x': 0, 'text-margin-y': 7, 'padding': '0px', 'events': 'no',
  814. 'z-index-compare': 'manual', 'z-index': 2
  815. }},
  816. {selector: 'node[type="floorframe"]', style: {
  817. 'background-opacity': d ? 0.04 : 0.025, 'background-color': d ? '#5b7bb0' : '#8fa6c4',
  818. 'border-width': 1.1, 'border-style': 'dashed', 'border-color': 'data(bd)',
  819. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center', 'text-wrap': 'none',
  820. 'font-size': 11.5, 'font-weight': 800, 'color': d ? '#a9c1e3' : '#425a78',
  821. 'text-margin-x': 0, 'text-margin-y': 6, 'padding': '0px', 'events': 'no',
  822. 'z-index-compare': 'manual', 'z-index': 3
  823. }},
  824. {selector: 'node[type="root"]', style: {
  825. 'background-opacity': d ? 0.02 : 0.012, 'background-color': d ? '#7aa0d8' : '#8ea6c2',
  826. 'border-width': 2.2, 'border-style': 'solid', 'border-color': d ? '#476492' : '#9fb0c6',
  827. 'label': 'data(label)', 'text-valign': 'top', 'text-halign': 'center',
  828. 'font-size': 28, 'font-weight': 900, 'color': d ? '#cfe0ff' : '#33465f',
  829. 'text-margin-y': 10, 'events': 'no', 'z-index-compare': 'manual', 'z-index': 0
  830. }},
  831. {selector: 'node[type="roottitle"]', style: {
  832. 'width': 'data(w)', 'height': 20, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  833. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  834. 'font-size': 24, 'font-weight': 900, 'color': d ? '#cfe0ff' : '#33465f', 'events': 'no',
  835. 'z-index-compare': 'manual', 'z-index': 5
  836. }},
  837. {selector: 'node[type="nettitle"]', style: {
  838. 'width': 'data(w)', 'height': 20, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  839. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  840. 'font-size': 20, 'font-weight': 900, 'color': d ? '#dbe9ff' : '#29425f', 'events': 'no',
  841. 'z-index-compare': 'manual', 'z-index': 5
  842. }},
  843. {selector: 'node[type="wslabel"]', style: {
  844. 'width': 'data(w)', 'height': 16, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  845. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  846. 'font-size': 15, 'font-weight': 900, 'color': d ? '#d7e6ff' : '#2f4560', 'events': 'no',
  847. 'z-index-compare': 'manual', 'z-index': 5
  848. }},
  849. {selector: 'node[type="floorlabel"]', style: {
  850. 'width': 'data(w)', 'height': 16, 'shape': 'rectangle', 'background-opacity': 0, 'border-width': 0,
  851. 'label': 'data(label)', 'text-valign': 'center', 'text-halign': 'center', 'text-wrap': 'none',
  852. 'font-size': 11, 'font-weight': 800, 'color': d ? '#a9c1e3' : '#425a78', 'events': 'no',
  853. 'z-index-compare': 'manual', 'z-index': 5
  854. }},
  855. {selector: 'node[type="tile"]', style: {
  856. 'width': 'data(w)', 'height': 'data(h)', 'shape': 'round-rectangle',
  857. 'background-color': 'data(bg)', 'background-opacity': 0.97,
  858. 'border-width': 2.5, 'border-color': 'data(bd)',
  859. 'label': 'data(label)', 'color': 'data(fg)',
  860. 'font-size': 16, 'font-weight': 700, 'text-valign': 'center', 'text-halign': 'center',
  861. 'text-wrap': 'wrap', 'text-max-width': TILE_W - 26, 'line-height': 1.45,
  862. 'padding': '6px', 'overlay-opacity': 0, 'z-index-compare': 'manual', 'z-index': 20
  863. }},
  864. {selector: 'node[type="tile"].alarm', style: {'border-width': 5}},
  865. {selector: 'node[type="tile"].core', style: {'border-width': 3.5}},
  866. {selector: 'node[type="ghost"]', style: {
  867. 'width': 190, 'height': 40, 'shape': 'round-rectangle',
  868. 'background-color': d ? '#52667f' : '#c8d3e2', 'background-opacity': 0.55,
  869. 'border-width': 1.2, 'border-style': 'dashed', 'border-color': d ? '#7d93ad' : '#8fa3bc',
  870. 'label': 'data(label)', 'color': d ? '#dce8fa' : '#3b4f68',
  871. 'font-size': 11, 'font-weight': 600, 'text-wrap': 'wrap', 'text-max-width': 176,
  872. 'z-index-compare': 'manual', 'z-index': 15
  873. }},
  874. {selector: 'node[type="edgepoint"]', style: {
  875. 'width': 1, 'height': 1, 'opacity': 0, 'events': 'no'
  876. }},
  877. {selector: 'node[type="term"]', style: {
  878. 'width': 7, 'height': 7, 'shape': 'ellipse', 'background-color': 'data(bg)',
  879. 'border-width': 1, 'border-color': d ? '#2a3648' : '#cfd8e3',
  880. 'label': 'data(label)', 'font-size': 9, 'font-weight': 700,
  881. 'color': d ? '#eaf1fb' : '#182c44',
  882. 'text-valign': 'bottom', 'text-halign': 'center', 'text-margin-y': 4,
  883. 'text-wrap': 'wrap', 'text-max-width': 160,
  884. 'text-background-color': d ? '#0d1b2a' : '#ffffff', 'text-background-opacity': 0.9,
  885. 'text-background-padding': '2px',
  886. 'z-index-compare': 'manual', 'z-index': 30
  887. }},
  888. {selector: 'edge[type="tilelink"]', style: {
  889. 'width': 'data(w)', 'line-color': 'data(color)', 'opacity': 0.55,
  890. 'curve-style': 'bezier', 'target-arrow-shape': 'none',
  891. 'z-index-compare': 'manual', 'z-index': 5
  892. }},
  893. {selector: 'edge[type="ghost"]', style: {
  894. 'width': 1.2, 'line-color': d ? '#6b809b' : '#a9b6c8', 'line-style': 'dashed', 'opacity': 0.7,
  895. 'curve-style': 'bezier', 'target-arrow-shape': 'none',
  896. 'z-index-compare': 'manual', 'z-index': 8
  897. }},
  898. {selector: 'edge[type="uplink"]', style: {
  899. 'width': 'data(w)', 'line-color': 'data(color)', 'line-style': 'data(ls)', 'opacity': 0.95,
  900. 'curve-style': 'bezier', 'target-arrow-shape': 'none',
  901. 'label': 'data(lbl)', 'font-size': 10, 'font-weight': 700,
  902. 'color': d ? '#dce8fa' : '#25405f',
  903. 'text-background-color': d ? '#0d1b2a' : '#ffffff', 'text-background-opacity': 0.88,
  904. 'text-background-padding': '2px', 'text-rotation': 'autorotate',
  905. 'z-index-compare': 'manual', 'z-index': 40
  906. }},
  907. {selector: 'edge', style: {
  908. 'width': 'data(w)', 'line-color': 'data(color)', 'line-style': 'data(ls)',
  909. 'curve-style': 'bezier', 'opacity': 0.92, 'target-arrow-shape': 'none',
  910. 'z-index-compare': 'manual', 'z-index': 12
  911. }},
  912. {selector: 'edge[type="link"]', style: {
  913. 'width': 'data(w)', 'line-color': 'data(color)', 'line-style': 'data(ls)',
  914. 'opacity': 0.62, 'curve-style': 'straight',
  915. 'source-endpoint': '0% 50%', 'target-endpoint': '0% 50%',
  916. 'target-arrow-shape': 'none', 'z-index-compare': 'manual', 'z-index': 1
  917. }},
  918. {selector: 'edge[type="term"]', style: {
  919. 'width': 0.7, 'line-color': d ? '#3b4a5e' : '#c5cfdb', 'opacity': 0.55,
  920. 'curve-style': 'bezier', 'z-index-compare': 'manual', 'z-index': 11
  921. }},
  922. {selector: 'node.alarm', style: {'border-width': 6}},
  923. {selector: 'node.dim', style: {'opacity': 0.12}},
  924. {selector: 'edge.dim', style: {'opacity': 0.08}},
  925. {selector: 'edge.hl', style: {'width': 5, 'line-color': '#FFD54A', 'opacity': 1, 'z-index-compare': 'manual', 'z-index': 45}},
  926. {selector: 'node.lat-warn', style: {'border-color': '#F39C12'}},
  927. {selector: 'node.lat-bad', style: {'border-color': '#E74C3C', 'border-width': 6}},
  928. {selector: 'node.hl', style: {'border-color': '#ff0', 'border-width': 7, 'overlay-color': '#ff0', 'overlay-opacity': 0.25, 'overlay-padding': 6}},
  929. {selector: 'node.pathhl', style: {'border-width': 5, 'border-color': '#FFD54A', 'overlay-color': '#FFD54A', 'overlay-opacity': 0.2, 'overlay-padding': 4}},
  930. {selector: 'edge.pathhl', style: {'width': 5.5, 'line-color': '#FFD54A', 'opacity': 1}},
  931. {selector: 'edge.detail', style: {'opacity': 0.72, 'curve-style': 'straight', 'source-endpoint': '0% 50%', 'target-endpoint': '0% 50%'}},
  932. {selector: 'node[type="switch"]', style: {
  933. 'background-color': function (e) { return e.data('bg'); },
  934. 'text-max-width': 'data(tw)', 'text-wrap': 'none',
  935. 'text-halign': 'center', 'font-size': 10.5
  936. }},
  937. {selector: 'node[type="switch"].root', style: {'text-wrap': 'wrap'}}
  938. ];
  939. }
  940. /* ---------------- render ---------------- */
  941. // One tall column chart cannot be squeezed into a wide window without
  942. // wasting half the canvas. The initial view fits the chart WIDTH and
  943. // anchors at the top (core switches first); the user can pan down or press
  944. // "适应窗口" to see the entire graph. This keeps labels readable.
  945. function initialView() {
  946. if (!cy) return;
  947. var bb = cy.elements().boundingBox();
  948. if (!bb || !bb.w || !bb.h) return;
  949. var zw = (cy.width() - 30) / bb.w;
  950. var zh = (cy.height() - 30) / bb.h;
  951. var tall = (bb.h * zw > cy.height() * 1.5);
  952. var z = tall ? zw * 0.95 : Math.min(zw, zh);
  953. cy.zoom({level: z});
  954. if (tall) {
  955. cy.pan({x: 15 - bb.x * z, y: 28 - bb.y * z});
  956. } else {
  957. cy.pan({x: (cy.width() - bb.w * z) / 2 - bb.x * z, y: (cy.height() - bb.h * z) / 2 - bb.y * z});
  958. }
  959. }
  960. function applyElements(els, keepView) {
  961. if (!cy) {
  962. cy = cytoscape({
  963. container: el('l2-cy'),
  964. elements: els,
  965. style: styleFor(dark),
  966. layout: {name: 'preset', fit: false},
  967. wheelSensitivity: 0.2,
  968. minZoom: 0.02, maxZoom: 4
  969. });
  970. bindCy();
  971. setTimeout(initialView, 0);
  972. } else {
  973. var z = cy.zoom(), p = cy.pan();
  974. cy.elements().remove();
  975. cy.add(els);
  976. cy.style(styleFor(dark));
  977. cy.layout({name: 'preset', fit: false}).run();
  978. if (keepView) { cy.zoom(z); cy.pan(p); }
  979. else { initialView(); }
  980. }
  981. }
  982. function fitGroup(label) {
  983. if (!cy || !label) return;
  984. var eles = cy.nodes().filter(function (n) {
  985. return n.data('blockGroup') === label || n.data('group') === label;
  986. });
  987. if (eles.length) cy.fit(eles, 70);
  988. }
  989. function render(snap) {
  990. if (!snap || !snap.nodes) {
  991. el('l2-cy').innerHTML = '<div class="l2-empty">' + t('l2.no_data', 'No data') + '</div>';
  992. return;
  993. }
  994. lastSnap = snap;
  995. renderFull(snap);
  996. updateStats(snap);
  997. buildLegend();
  998. buildAlarms(snap);
  999. buildOffline(snap);
  1000. buildTerminals(snap);
  1001. }
  1002. function renderFull(snap) {
  1003. var L = computeFull(snap), els = [];
  1004. if (!L.placements.length) { applyElements([], false); return; }
  1005. var byId = {};
  1006. L.placements.forEach(function (p) { byId[p.node.id] = p; });
  1007. els.push({group: 'nodes', data: {id: '__root', type: 'root', label: '', w: L.root.w, h: L.root.h},
  1008. position: {x: L.root.w / 2, y: L.root.h / 2}, selectable: false, grabbable: false});
  1009. els.push({group: 'nodes', data: {id: '__roottitle', type: 'roottitle', label: CFG.root_label || 'COBCO', w: L.root.w, h: 20},
  1010. position: {x: L.root.w / 2, y: 22}, selectable: false, grabbable: false});
  1011. L.sections.forEach(function (sec, si) {
  1012. els.push({group: 'nodes', data: {
  1013. id: '__net_' + si, type: 'netframe', label: '', w: sec.w, h: sec.h, net: sec.key, bd: sec.color
  1014. }, position: {x: sec.x + sec.w / 2, y: sec.y + sec.h / 2}, selectable: false, grabbable: false});
  1015. els.push({group: 'nodes', data: {id: '__nettitle_' + si, type: 'nettitle', label: sec.label, w: sec.w, h: 20},
  1016. position: {x: sec.x + sec.w / 2, y: sec.y + 21}, selectable: false, grabbable: false});
  1017. });
  1018. L.frames.forEach(function (f) {
  1019. els.push({group: 'nodes', data: {
  1020. id: f.id, type: f.type, label: '', w: f.w, h: f.h, group: f.group || '', net: f.net, bd: f.color || netColor(f.net)
  1021. }, position: {x: f.x + f.w / 2, y: f.y + f.h / 2}, selectable: false, grabbable: false});
  1022. var tt = f.type === 'floorframe' ? 'floorlabel' : 'wslabel';
  1023. var ty = f.type === 'floorframe' ? 11 : 18;
  1024. els.push({group: 'nodes', data: {id: 'label_' + f.id, type: tt, label: f.label, w: f.w, h: 16},
  1025. position: {x: f.x + f.w / 2, y: f.y + ty}, selectable: false, grabbable: false});
  1026. });
  1027. L.placements.forEach(function (p) {
  1028. var n = p.node, cls = [];
  1029. var bg = p.role === 'core' ? TIER_BG.core : (p.role === 'main' ? '#2E75B6' : (p.role === 'dist' ? TIER_BG.dist : TIER_BG.access));
  1030. var bd = bg;
  1031. if (n.alarms && n.alarms.length) { cls.push('alarm'); bd = '#E45959'; }
  1032. if (n.latency_ms != null) {
  1033. if (+n.latency_ms > LATB) cls.push('lat-bad');
  1034. else if (+n.latency_ms > LATW) cls.push('lat-warn');
  1035. }
  1036. if (p.role === 'core') cls.push('root');
  1037. els.push({group: 'nodes', data: {
  1038. id: n.id, type: 'switch', name: n.name, ip: n.ip, tier: n.tier, depth: n.depth, hostid: n.hostid, oper: n.oper,
  1039. maxsev: n.maxsev, alarms: n.alarms || [], term_online: n.term_online, term_offline: n.term_offline, latency_ms: n.latency_ms,
  1040. label: switchLabel(n, p.role, p.net), tw: p.w - 12, bg: bg, bd: bd, w: p.w, h: p.h,
  1041. group: p.group + ' · ' + netLabel(p.net), blockGroup: p.group, net: p.net, role: p.role
  1042. }, position: {x: p.x, y: p.y}, classes: cls.join(' ')});
  1043. });
  1044. // Every protocol-discovered link = one straight segment. Cytoscape's
  1045. // percentage endpoints are unreliable with preset labels, so use two
  1046. // invisible anchor nodes placed exactly on the label left-edge midpoint.
  1047. // The labels paint on top, so a parent line starts under the parent label
  1048. // and ends exactly at the child's left edge.
  1049. pathParent = buildParents(snap, L);
  1050. (snap.edges || []).forEach(function (e, i) {
  1051. var ps = byId[e.source], pt = byId[e.target];
  1052. if (!ps || !pt) return;
  1053. var sp = 'sp_' + i, tp = 'tp_' + i;
  1054. els.push({group: 'nodes', data: {id: sp, type: 'edgepoint'}, position: {x: ps.x - ps.w / 2, y: ps.y}, selectable: false, grabbable: false});
  1055. els.push({group: 'nodes', data: {id: tp, type: 'edgepoint'}, position: {x: pt.x - pt.w / 2, y: pt.y}, selectable: false, grabbable: false});
  1056. var col = speedColor(e.speed, e.state);
  1057. els.push({group: 'edges', data: {
  1058. id: 'e_' + i, type: 'link', source: sp, target: tp, p: e.source, c: e.target,
  1059. speed: e.speed, state: e.state, a_port: e.a_port, b_port: e.b_port,
  1060. color: col, ls: (e.state && e.state !== 'up') ? 'dashed' : 'solid', w: Math.min(4, speedWidth(e.speed))
  1061. }});
  1062. });
  1063. if (showTerm) addTerminals(L, byId, els);
  1064. applyElements(els, true);
  1065. if (focusGroupLabel) {
  1066. setTimeout(function () { fitGroup(focusGroupLabel); }, 80);
  1067. focusGroupLabel = null;
  1068. }
  1069. }
  1070. function addTerminals(L, byId, els) {
  1071. var bySw = {};
  1072. ((lastSnap && lastSnap.terminals) || []).forEach(function (tm) {
  1073. if (!byId[tm.sw_ip]) return;
  1074. if (onlyOff && terminalOnline(tm)) return;
  1075. (bySw[tm.sw_ip] = bySw[tm.sw_ip] || []).push(tm);
  1076. });
  1077. Object.keys(bySw).forEach(function (sw) {
  1078. var p = byId[sw]; if (!p || p.role === 'core' || p.role === 'main') return;
  1079. bySw[sw].sort(function (a, b) { return (terminalOnline(a) === terminalOnline(b)) ? 0 : (terminalOnline(a) ? -1 : 1); });
  1080. // A search hit is pinned into the visible 24 so any MAC in the snapshot
  1081. // can be located even when its switch has more than 24 terminals.
  1082. if (pinnedTerm) {
  1083. for (var pi = 0; pi < bySw[sw].length; pi++) {
  1084. if (bySw[sw][pi].mac === pinnedTerm) {
  1085. if (pi > 0) { var pin = bySw[sw].splice(pi, 1)[0]; bySw[sw].unshift(pin); }
  1086. break;
  1087. }
  1088. }
  1089. }
  1090. bySw[sw].slice(0, 24).forEach(function (tm, k) {
  1091. var col = k % 12, row = Math.floor(k / 12);
  1092. var x = p.x - p.w / 2 + 16 + col * 9;
  1093. var y = p.y + 16 + row * 9;
  1094. els.push({group: 'nodes', data: {
  1095. id: 't_' + tm.mac, type: 'term', bg: terminalOnline(tm) ? '#2ECC71' : '#95a5a6',
  1096. mac: tm.mac, ip: tm.ip, online: terminalOnline(tm), speed: tm.speed,
  1097. sw_name: tm.sw_name, port: tm.port, label: '', termText: terminalText(tm)
  1098. }, position: {x: x, y: y}, selectable: false});
  1099. els.push({group: 'edges', data: {id: 'te_' + tm.mac, type: 'term', source: sw, target: 't_' + tm.mac}});
  1100. });
  1101. });
  1102. }
  1103. function renderOverview(snap) {
  1104. var O = computeOverview(snap), els = [], idx = {};
  1105. var nb = el('l2-net-tabs'); if (nb) { nb.style.display = 'none'; nb.innerHTML = ''; }
  1106. if (O.root) {
  1107. els.push({group: 'nodes', data: {id: '__root', type: 'root', label: CFG.root_label || 'COBCO', w: O.root.w, h: O.root.h},
  1108. position: {x: O.root.cx, y: O.root.cy}, selectable: false, grabbable: false});
  1109. }
  1110. O.tiles.forEach(function (tile, i) {
  1111. var s = O.stats[tile.label] || {nodes: [], alarms: 0, offline: 0, maxsev: -1};
  1112. idx[tile.label] = 'grp_' + i;
  1113. var isCore = /core/i.test(tile.label) || /data\s*center/i.test(tile.label);
  1114. var bd = s.alarms ? '#E45959' : (dark ? '#41597c' : '#b9c8dc');
  1115. var bg = isCore ? TIER_BG.core : (dark ? '#22344e' : '#eef3fb');
  1116. var fg = isCore ? '#ffffff' : (dark ? '#dfe9fb' : '#1e3352');
  1117. var lbl = tile.label + '\n' + s.nodes.length + ' ' + t('l2.unit_sw', 'sw') +
  1118. (s.up ? ' ↑ ' + s.up : '') + (s.alarms ? ' ⚠ ' + s.alarms : '') + (s.offline ? ' ◌ ' + s.offline : '');
  1119. var cls = [];
  1120. if (s.alarms) cls.push('alarm');
  1121. if (isCore) cls.push('core');
  1122. els.push({group: 'nodes', data: {
  1123. id: idx[tile.label], type: 'tile', group: tile.label,
  1124. n: s.nodes.length, alarms: s.alarms, offline: s.offline, maxsev: s.maxsev, up: s.up,
  1125. label: lbl, bg: bg, fg: fg, bd: bd, w: TILE_W, h: TILE_H
  1126. }, position: {x: tile.x + tile.w / 2, y: tile.y + tile.h / 2}, classes: cls.join(' ')});
  1127. });
  1128. applyElements(els);
  1129. }
  1130. function renderNetTabs(D) {
  1131. var box = el('l2-net-tabs');
  1132. if (!box) return;
  1133. box.innerHTML = '';
  1134. if (!D.nets || D.nets.length < 2) { box.style.display = 'none'; return; }
  1135. box.style.display = 'flex';
  1136. D.nets.forEach(function (n) {
  1137. var b = document.createElement('button');
  1138. b.type = 'button';
  1139. b.className = 'l2-net-tab' + (n.key === D.activeNet ? ' active' : '');
  1140. b.textContent = networkLabel(n.key) + ' · ' + n.count + ' ' + t('l2.unit_sw', 'sw');
  1141. b.addEventListener('click', function () { detailNet = n.key; render(lastSnap); });
  1142. box.appendChild(b);
  1143. });
  1144. }
  1145. function renderDetail(snap) {
  1146. var D = computeDetail(snap, viewGroup), els = [];
  1147. renderNetTabs(D);
  1148. function frameEl(id, type, fr) {
  1149. els.push({group: 'nodes', data: {id: id, type: type, label: fr.label, w: fr.w, h: fr.h},
  1150. position: {x: fr.x + fr.w / 2, y: fr.y + fr.h / 2}, selectable: false, grabbable: false});
  1151. }
  1152. frameEl('__ws', 'wsframe', {x: D.frames.workshop.x, y: 36, w: D.frames.workshop.w, h: D.frames.workshop.h + 36, label: D.frames.workshop.label});
  1153. if (D.frames.dist) frameEl('__dist', 'floorframe', D.frames.dist);
  1154. D.floors.forEach(function (f, i) { frameEl('__floor_' + i, 'floorframe', f.frame); });
  1155. (D.ghosts || []).forEach(function (g) {
  1156. var nm = (g.node && g.node.name) || g.id;
  1157. var ip = (g.node && g.node.ip) || '';
  1158. var tail = String(nm).split(/[-\s]+/).filter(Boolean).slice(-1)[0] || '';
  1159. var short = (tail ? tail + ' · ' : '') + ip;
  1160. els.push({group: 'nodes', data: {id: g.id, type: 'ghost', label: short}, position: {x: g.x, y: g.y}, selectable: false, grabbable: false});
  1161. els.push({group: 'edges', data: {
  1162. id: 'ghe_' + g.id, type: 'uplink', source: g.id, target: g.to,
  1163. speed: g.speed, state: g.state, lbl: speedText(g.speed),
  1164. color: speedColor(g.speed, g.state), ls: (g.state && g.state !== 'up') ? 'dashed' : 'solid',
  1165. w: Math.max(2.6, speedWidth(g.speed))
  1166. }});
  1167. });
  1168. var switchIds = {};
  1169. D.nodes.forEach(function (n, ni) {
  1170. switchIds[n.id] = true;
  1171. var p = D.pos[n.id] || {x: 0, y: 0};
  1172. var tier = n.tier || 'access';
  1173. var tkey = (tier.indexOf('dist') === 0) ? 'dist' : (tier.indexOf('core') === 0 ? 'core' : 'access');
  1174. var isRoot = D.dists && D.dists.length && n.id === D.dists[0].id;
  1175. var cls = [];
  1176. var bd = (dark ? TIER_BG_DARK[tkey] : TIER_BG[tkey]) || '#555';
  1177. var bg = (dark ? TIER_BG_DARK[tkey] : TIER_BG[tkey]) || '#777';
  1178. if (!isRoot && ni % 2 === 1) bg = dark ? '#4f8a3a' : '#6ca75a';
  1179. if (n.alarms && n.alarms.length) {
  1180. cls.push('alarm');
  1181. bd = '#E45959';
  1182. }
  1183. if (n.latency_ms != null) {
  1184. if (+n.latency_ms > LATB) cls.push('lat-bad');
  1185. else if (+n.latency_ms > LATW) cls.push('lat-warn');
  1186. }
  1187. if (isRoot) cls.push('root');
  1188. els.push({group: 'nodes', data: {
  1189. id: n.id, type: 'switch', name: n.name, ip: n.ip, tier: tier, depth: n.depth,
  1190. hostid: n.hostid, oper: n.oper, maxsev: n.maxsev, alarms: n.alarms || [],
  1191. term_online: n.term_online, term_offline: n.term_offline, latency_ms: n.latency_ms,
  1192. label: isRoot ? rootLabel(n) : rowLabel(n), tw: isRoot ? 150 : 360,
  1193. bg: bg, bd: isRoot ? bd : '#25501e',
  1194. w: isRoot ? 170 : 380, h: isRoot ? 50 : 24, group: viewGroup
  1195. }, position: p, classes: cls.join(' ')});
  1196. });
  1197. D.internal.forEach(function (e, i) {
  1198. var root = D.dists && D.dists[0];
  1199. if (root && (e.source === root.id || e.target === root.id)) {
  1200. var childId = e.source === root.id ? e.target : e.source;
  1201. var pp = D.pos[root.id], cp = D.pos[childId];
  1202. if (pp && cp) {
  1203. var sp = 'sp_' + i, tp = 'tp_' + i;
  1204. // Exact left-edge midpoints, straight line. The parent label is
  1205. // allowed to cover the line where it exits the parent.
  1206. els.push({group: 'nodes', data: {id: sp, type: 'edgepoint'}, position: {x: pp.x - 86, y: pp.y}, selectable: false, grabbable: false});
  1207. els.push({group: 'nodes', data: {id: tp, type: 'edgepoint'}, position: {x: cp.x - 191, y: cp.y}, selectable: false, grabbable: false});
  1208. els.push({group: 'edges', data: {
  1209. id: 'e_' + i, type: 'detail', source: sp, target: tp, p: root.id, c: childId,
  1210. speed: e.speed, state: e.state, a_port: e.a_port, b_port: e.b_port,
  1211. color: speedColor(e.speed, e.state), ls: (e.state && e.state !== 'up') ? 'dashed' : 'solid',
  1212. w: Math.min(2.4, speedWidth(e.speed))
  1213. }, classes: 'detail'});
  1214. return;
  1215. }
  1216. }
  1217. els.push({group: 'edges', data: {
  1218. id: 'e_' + i, source: e.source, target: e.target, speed: e.speed, state: e.state,
  1219. a_port: e.a_port, b_port: e.b_port,
  1220. color: speedColor(e.speed, e.state), ls: (e.state && e.state !== 'up') ? 'dashed' : 'solid',
  1221. w: Math.min(2.4, speedWidth(e.speed))
  1222. }, classes: 'detail'});
  1223. });
  1224. if (showTerm) {
  1225. var bySw = {};
  1226. (snap.terminals || []).forEach(function (tm) {
  1227. if (!switchIds[tm.sw_ip]) return;
  1228. if (onlyOff && tm.online) return;
  1229. (bySw[tm.sw_ip] = bySw[tm.sw_ip] || []).push(tm);
  1230. });
  1231. Object.keys(bySw).forEach(function (sw) {
  1232. var base = D.pos[sw]; if (!base) return;
  1233. bySw[sw].sort(function (a, b) { return (a.online === b.online) ? 0 : (a.online ? -1 : 1); });
  1234. bySw[sw].forEach(function (tm, k) {
  1235. var col = k % 9, row = Math.floor(k / 9);
  1236. var x = base.x - 54 + col * 13;
  1237. var y = base.y + NODE_H / 2 + 16 + row * 13;
  1238. els.push({group: 'nodes', data: {id: 't_' + tm.mac, type: 'term', bg: tm.online ? '#2ECC71' : '#95a5a6', mac: tm.mac, ip: tm.ip, online: tm.online},
  1239. position: {x: x, y: y}, selectable: false});
  1240. els.push({group: 'edges', data: {id: 'te_' + tm.mac, type: 'term', source: sw, target: 't_' + tm.mac}});
  1241. });
  1242. });
  1243. }
  1244. pathParent = D.parentOf || {};
  1245. lockedPath = null;
  1246. applyElements(els);
  1247. }
  1248. /* ---------------- side panels & stats ---------------- */
  1249. function updateStats(snap) {
  1250. var s = snap.stats || {};
  1251. var txt = '● ' + (s.switches || 0) + ' | ⇄ ' + (s.edges || 0) + ' | ' +
  1252. (s.term_total || 0) + '(' + (s.term_online || 0) + '/' + (s.term_offline || 0) + ') | ⚠ ' + (s.alarms || 0);
  1253. var up = snap.generated_iso ? (' · ' + t('l2.updated', 'Updated') + ' ' + snap.generated_iso) : '';
  1254. el('l2-stats').textContent = txt + up;
  1255. }
  1256. function buildLegend() {
  1257. var h = '';
  1258. function sw(c, label, dashed) { return '<div class="lg-row"><span class="lg-line' + (dashed ? ' lg-dash' : '') + '" style="border-top-color:' + c + '"></span>' + label + '</div>'; }
  1259. h += '<div class="lg-title">' + t('l2.legend_speed', 'Link speed') + '</div>';
  1260. h += sw(colors['100'], '100M') + sw(colors['1000'], '1G') + sw(colors['10000'], '10G') + sw(colors['20000'], '20G+');
  1261. h += sw(colors.unknown, t('lbl.color_unknown', 'Unknown'));
  1262. h += sw(colors.down, t('lbl.color_down', 'Down'), true);
  1263. h += '<div class="lg-title">' + t('l2.legend_tier', 'Tier') + '</div>';
  1264. h += '<div class="lg-row"><span class="lg-box" style="background:' + TIER_BG.core + '"></span>' + t('l2.core', 'Core') +
  1265. '<span class="lg-box" style="background:#2E75B6;margin-left:8px"></span>' + t('l2.main', 'Main switch') +
  1266. '<span class="lg-box" style="background:' + TIER_BG.dist + ';margin-left:8px"></span>' + t('l2.dist', 'Distribution') +
  1267. '<span class="lg-box" style="background:' + TIER_BG.access + ';margin-left:8px"></span>' + t('l2.access', 'Access') + '</div>';
  1268. h += '<div class="lg-title">' + t('l2.legend_lat', 'Latency') + '</div>';
  1269. h += '<div class="lg-row"><span class="lg-box" style="background:#F39C12;border-radius:2px"></span>&gt;' + LATW + 'ms' +
  1270. '<span class="lg-box" style="background:#E74C3C;border-radius:2px;margin-left:8px"></span>&gt;' + LATB + 'ms</div>';
  1271. h += '<div class="lg-row"><span class="lg-box" style="background:#E45959;border-radius:2px"></span>' + t('l2.alarms', 'Alarms') + '</div>';
  1272. h += '<div class="lg-row"><span class="lg-box" style="background:#2ECC71;border-radius:50%"></span>' + t('l2.term_on', 'Online') +
  1273. '<span class="lg-box" style="background:#95a5a6;border-radius:50%;margin-left:8px"></span>' + t('l2.term_off', 'Offline') + '</div>';
  1274. h += '<div class="lg-row" style="opacity:.72;margin-top:4px">' + t('l2.click_hint', 'Hover a switch to highlight its full upstream path') + '</div>';
  1275. el('l2-legend').innerHTML = h;
  1276. }
  1277. function buildAlarms(snap) {
  1278. var items = [];
  1279. (snap.nodes || []).forEach(function (n) {
  1280. if (n.maxsev != null && n.maxsev >= 0 && n.alarms && n.alarms.length) {
  1281. n.alarms.forEach(function (a) {
  1282. items.push({sev: n.maxsev, title: (a.name || a.description || ''), host: n.name, ip: n.ip, id: n.id, hostid: n.hostid});
  1283. });
  1284. }
  1285. });
  1286. el('l2-alarm-count').textContent = items.length;
  1287. if (!items.length) { el('l2-alarm-list').innerHTML = '<div class="panel-empty">' + t('l2.alarm_empty', 'No active alarms.') + '</div>'; return; }
  1288. items.sort(function (a, b) { return b.sev - a.sev; });
  1289. var h = '';
  1290. items.forEach(function (it) {
  1291. var col = SEV_COLORS[Math.max(0, Math.min(5, it.sev))] || '#999';
  1292. h += '<div class="alarm-row" data-id="' + (it.id || '') + '" data-hostid="' + (it.hostid || '') + '">' +
  1293. '<span class="alarm-dot" style="background:' + col + '"></span>' +
  1294. '<div class="alarm-main"><div class="alarm-title">' + esc(it.title) + '</div>' +
  1295. '<div class="alarm-sub">' + esc(it.host || '') + (it.ip ? ' · ' + esc(it.ip) : '') + '</div></div></div>';
  1296. });
  1297. var box = el('l2-alarm-list');
  1298. box.innerHTML = h;
  1299. box.querySelectorAll('.alarm-row').forEach(function (r) {
  1300. r.addEventListener('click', function () {
  1301. var id = r.getAttribute('data-id');
  1302. if (id) revealById(id);
  1303. else { var hid = r.getAttribute('data-hostid'); if (hid) window.open(META.zabbixHostUrl.replace('__HOSTID__', hid), '_blank'); }
  1304. });
  1305. });
  1306. }
  1307. function buildOffline(snap) {
  1308. var off = (snap.terminals || []).filter(function (tm) { return !terminalOnline(tm); });
  1309. el('l2-offline-count').textContent = off.length;
  1310. if (!off.length) { el('l2-offline-list').innerHTML = '<div class="panel-empty">' + t('l2.offline_empty', 'No offline terminals.') + '</div>'; return; }
  1311. var h = '';
  1312. off.forEach(function (tm) {
  1313. h += '<div class="off-row" data-mac="' + esc(tm.mac) + '">' +
  1314. '<div class="off-main"><div class="off-mac">' + esc(tm.mac) + '</div>' +
  1315. '<div class="off-sub">' + esc(speedText(tm.speed)) + ' · ' + esc(tm.sw_name || tm.sw_ip) + ' · ' + esc(tm.port || '') + '</div></div></div>';
  1316. });
  1317. var box = el('l2-offline-list');
  1318. box.innerHTML = h;
  1319. box.querySelectorAll('.off-row').forEach(function (r) {
  1320. r.addEventListener('click', function () {
  1321. var mac = r.getAttribute('data-mac');
  1322. revealById('t_' + mac);
  1323. });
  1324. });
  1325. }
  1326. function buildTerminals(snap) {
  1327. var list = (snap.terminals || []).filter(function (tm) { return !onlyOff || !terminalOnline(tm); });
  1328. if (el('l2-term-count')) el('l2-term-count').textContent = list.length;
  1329. var box = el('l2-term-list');
  1330. if (!box) return;
  1331. if (!showTerm) {
  1332. box.innerHTML = '<div class="panel-empty">' + t('l2.show_term', 'Show terminals') + '</div>';
  1333. return;
  1334. }
  1335. if (!list.length) {
  1336. box.innerHTML = '<div class="panel-empty">' + t('l2.no_data', 'No data') + '</div>';
  1337. return;
  1338. }
  1339. list.sort(function (a, b) {
  1340. var x = String(a.sw_name || a.sw_ip || '').localeCompare(String(b.sw_name || b.sw_ip || ''));
  1341. return x || String(a.mac).localeCompare(String(b.mac));
  1342. });
  1343. var h = '';
  1344. list.forEach(function (tm) {
  1345. var on = terminalOnline(tm);
  1346. h += '<div class="off-row term-row" data-mac="' + esc(tm.mac) + '">' +
  1347. '<span class="term-dot" style="background:' + (on ? '#2ECC71' : '#95a5a6') + '"></span>' +
  1348. '<div class="off-main"><div class="off-mac">' + esc(tm.mac) + '</div>' +
  1349. '<div class="off-sub"><span class="term-rate">' + esc(speedText(tm.speed)) + '</span> · ' +
  1350. (on ? t('l2.term_on', 'online') : t('l2.term_off', 'offline')) + ' · ' +
  1351. esc(tm.sw_name || tm.sw_ip || '') + ' · ' + esc(tm.port || '') + '</div></div></div>';
  1352. });
  1353. box.innerHTML = h;
  1354. box.querySelectorAll('.term-row').forEach(function (r) {
  1355. r.addEventListener('click', function () { revealById('t_' + r.getAttribute('data-mac')); });
  1356. });
  1357. }
  1358. function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c]; }); }
  1359. /* ---------------- interactions ---------------- */
  1360. function focusNode(id) {
  1361. if (!cy) return;
  1362. var n = cy.getElementById(id);
  1363. if (!n || n.empty() || n.length === 0) return;
  1364. cy.elements().removeClass('hl');
  1365. n.addClass('hl');
  1366. cy.animate({center: {eles: n}, zoom: Math.max(cy.zoom(), 1.1), duration: 380});
  1367. setTimeout(function () { n.removeClass('hl'); }, 2600);
  1368. }
  1369. function groupOfNodeId(id) {
  1370. var hit = (lastSnap && lastSnap.nodes || []).filter(function (n) { return n.id === id; })[0];
  1371. return hit ? groupOf(hit).label : null;
  1372. }
  1373. // Make sure a switch/terminal is visible (auto-opens its workshop from overview).
  1374. function revealById(id) {
  1375. if (!lastSnap) return;
  1376. id = String(id);
  1377. if (id.indexOf('t_') === 0) {
  1378. var tm = (lastSnap.terminals || []).filter(function (x) { return 't_' + x.mac === id; })[0];
  1379. if (!tm) return;
  1380. pinnedTerm = tm.mac;
  1381. showTerm = true;
  1382. if (el('l2-showterm')) el('l2-showterm').checked = true;
  1383. // A search hit must be visible even when the offline-only filter is on.
  1384. if (onlyOff && terminalOnline(tm)) {
  1385. onlyOff = false;
  1386. if (el('l2-onlyoff')) el('l2-onlyoff').checked = false;
  1387. }
  1388. if (!cy || cy.getElementById(id).empty()) render(lastSnap);
  1389. setTimeout(function () {
  1390. // Center the switch that the terminal hangs under, then flash the
  1391. // terminal dot so the exact port location is obvious.
  1392. focusNode(tm.sw_ip || id);
  1393. var tn = cy && cy.getElementById(id);
  1394. if (tn && tn.length) {
  1395. tn.addClass('hl');
  1396. setTimeout(function () { tn.removeClass('hl'); }, 2600);
  1397. }
  1398. }, 90);
  1399. } else {
  1400. focusNode(id);
  1401. }
  1402. }
  1403. function clearPath() {
  1404. if (!cy) return;
  1405. cy.elements().removeClass('dim pathhl');
  1406. lockedPath = null;
  1407. }
  1408. function highlightPath(nodeId) {
  1409. if (!cy) return;
  1410. var chain = [], id = nodeId, guard = 0;
  1411. while (id && guard++ < 40) {
  1412. chain.unshift(id);
  1413. id = pathParent[id] || null;
  1414. }
  1415. cy.elements('node[type="switch"], node[type="ghost"], edge').addClass('dim').removeClass('pathhl');
  1416. var nodes = cy.collection();
  1417. chain.forEach(function (cid) { var n = cy.getElementById(cid); if (n && n.length) nodes = nodes.union(n); });
  1418. nodes.removeClass('dim').addClass('pathhl');
  1419. var edges = cy.edges().filter(function (e) {
  1420. var p = e.data('p'), c = e.data('c');
  1421. if (p && c) return chain.indexOf(p) >= 0 && chain.indexOf(c) >= 0;
  1422. var s = e.data('source'), t = e.data('target');
  1423. return chain.indexOf(s) >= 0 && chain.indexOf(t) >= 0;
  1424. });
  1425. edges.removeClass('dim').addClass('pathhl');
  1426. }
  1427. function bindCy() {
  1428. cy.on('mouseover', 'node[type="switch"]', function (e) {
  1429. highlightPath(e.target.id());
  1430. var d = e.target.data();
  1431. var arr = d.alarms || [];
  1432. var sev = (d.maxsev != null && d.maxsev >= 0) ? ('<span style="color:' + SEV_COLORS[d.maxsev] + '">● ' + SEV_NAMES[d.maxsev] + '</span>') : '—';
  1433. var lat = (d.latency_ms != null) ? (d.latency_ms + ' ms') : '—';
  1434. var html = '<b>' + esc(d.name) + '</b><br>' + esc(d.ip) + ' · ' + esc(d.group || '') + '<br>' +
  1435. 'Tier: ' + esc(d.tier) + ' · ' + (d.oper || '') + '<br>' +
  1436. 'Latency: ' + lat + '<br>' +
  1437. 'Terminals: ' + (d.term_online || 0) + ' on / ' + (d.term_offline || 0) + ' off<br>' +
  1438. 'Alarm: ' + sev;
  1439. if (arr.length) html += '<hr>' + arr.map(function (a) { return esc(a.name || a.description || ''); }).join('<br>');
  1440. showTip(e, html);
  1441. });
  1442. cy.on('mouseout', 'node[type="switch"]', function () {
  1443. if (!lockedPath) clearPath();
  1444. hideTip();
  1445. });
  1446. cy.on('mouseover', 'edge:not([type="term"])', function (e) {
  1447. var d = e.target.data();
  1448. var sp = (parseFloat(d.speed) || 0) >= 1000 ? ((parseFloat(d.speed) / 1000) + 'G') : (d.speed + 'M');
  1449. showTip(e, 'Link ' + esc(d.a_port || '') + ' ↔ ' + esc(d.b_port || '') + '<br>' + sp + ' · ' + esc(d.state || ''));
  1450. });
  1451. cy.on('mouseout', 'edge', hideTip);
  1452. cy.on('mouseover', 'node[type="term"]', function (e) {
  1453. var d = e.target.data();
  1454. e.target.data('label', d.termText || '');
  1455. showTip(e, '<b>' + esc(t('l2.term_title', 'Terminal')) + ' ' + esc(d.mac || '') + '</b><br>' +
  1456. esc(t('l2.term_mac', 'MAC address')) + ': ' + esc(d.mac || '') + '<br>' +
  1457. esc(t('l2.term_ip', 'IP address')) + ': ' + esc(d.ip || '—') + '<br>' +
  1458. esc(t('l2.term_rate', 'Link rate')) + ': ' + esc(speedText(d.speed)) + '<br>' +
  1459. esc(t('l2.term_switch', 'Switch')) + ': ' + esc(d.sw_name || '—') + '<br>' +
  1460. esc(t('l2.term_port', 'Port')) + ': ' + esc(d.port || '—'));
  1461. });
  1462. cy.on('mouseout', 'node[type="term"]', function (e) {
  1463. e.target.data('label', '');
  1464. hideTip();
  1465. });
  1466. cy.on('tap', 'node[type="switch"]', function (e) {
  1467. lockedPath = e.target.id();
  1468. highlightPath(lockedPath);
  1469. });
  1470. cy.on('tap', 'node[type="wsframe"]', function (e) {
  1471. cy.fit(e.target, 60);
  1472. });
  1473. cy.on('tap', function (e) {
  1474. if (e.target === cy) clearPath();
  1475. });
  1476. cy.on('dbltap', 'node[type="switch"]', function (e) {
  1477. var hid = e.target.data('hostid');
  1478. if (hid) window.open(META.zabbixHostUrl.replace('__HOSTID__', hid), '_blank');
  1479. });
  1480. }
  1481. var SEV_NAMES = ['未分类','信息','警告','一般严重','严重','灾难'];
  1482. function showTip(e, html) {
  1483. var tip = el('l2-tip');
  1484. tip.innerHTML = html;
  1485. tip.style.display = 'block';
  1486. var p = e.renderedPosition || {x: 0, y: 0};
  1487. var box = el('l2-cy').getBoundingClientRect();
  1488. var x = box.left + p.x + 16, y = box.top + p.y + 16;
  1489. tip.style.left = x + 'px'; tip.style.top = y + 'px';
  1490. }
  1491. function hideTip() { el('l2-tip').style.display = 'none'; }
  1492. /* ---------------- search ---------------- */
  1493. function buildIndex(snap) {
  1494. var idx = [];
  1495. (snap.nodes || []).forEach(function (n) { idx.push({id: n.id, label: n.name, sub: n.ip, kind: 'sw'}); });
  1496. (snap.terminals || []).forEach(function (tm) {
  1497. idx.push({id: 't_' + tm.mac, label: tm.mac, sub: (tm.ip || '') + ' · ' + speedText(tm.speed) + ' · ' + (tm.sw_name || ''), kind: 'term', mac: tm.mac});
  1498. });
  1499. return idx;
  1500. }
  1501. var INDEX = [];
  1502. function doSearch(q) {
  1503. var box = el('l2-sug');
  1504. q = (q || '').trim().toLowerCase();
  1505. if (!q) { box.style.display = 'none'; box.innerHTML = ''; return; }
  1506. var hits = [];
  1507. var qn = q.replace(/[^a-z0-9]/g, '');
  1508. for (var i = 0; i < INDEX.length && hits.length < 14; i++) {
  1509. var it = INDEX[i];
  1510. var hay = ((it.label || '') + ' ' + (it.sub || '')).toLowerCase();
  1511. var hayN = hay.replace(/[^a-z0-9]/g, '');
  1512. if (hay.indexOf(q) >= 0 || (qn && hayN.indexOf(qn) >= 0)) hits.push(it);
  1513. }
  1514. if (!hits.length) { box.innerHTML = '<div class="sug-empty">—</div>'; box.style.display = 'block'; return; }
  1515. box.innerHTML = hits.map(function (h) {
  1516. return '<div class="sug-row" data-id="' + esc(h.id) + '"><span class="sug-kind ' + h.kind + '">' + (h.kind === 'sw' ? 'SW' : 'PC') + '</span>' +
  1517. '<span class="sug-lbl">' + esc(h.label) + '</span><span class="sug-sub">' + esc(h.sub || '') + '</span></div>';
  1518. }).join('');
  1519. box.style.display = 'block';
  1520. box.querySelectorAll('.sug-row').forEach(function (r) {
  1521. r.addEventListener('click', function () {
  1522. var id = r.getAttribute('data-id');
  1523. revealById(id);
  1524. box.style.display = 'none';
  1525. });
  1526. });
  1527. }
  1528. /* ---------------- toolbar wiring ---------------- */
  1529. function isZabbixDark() {
  1530. var html = document.documentElement;
  1531. var cs = String(html.getAttribute('color-scheme') || '').toLowerCase();
  1532. if (cs === 'dark') return true;
  1533. if (cs === 'light') return false;
  1534. var body = document.body;
  1535. var theme = [
  1536. html.getAttribute('theme'), html.getAttribute('data-theme'), html.className,
  1537. body ? body.getAttribute('theme') : '', body ? body.getAttribute('data-theme') : '',
  1538. body ? body.className : ''
  1539. ].join(' ');
  1540. return /dark/i.test(theme);
  1541. }
  1542. function applyTheme() {
  1543. var nd = isZabbixDark();
  1544. var changed = nd !== dark;
  1545. dark = nd;
  1546. var wrap = el('l2-wrap');
  1547. if (wrap) wrap.classList.toggle('l2-dark', dark);
  1548. if (changed && cy) cy.style(styleFor(dark));
  1549. }
  1550. function fitViewport() {
  1551. var wrap = el('l2-wrap');
  1552. if (!wrap) return;
  1553. var top = Math.max(0, wrap.getBoundingClientRect().top);
  1554. var h = Math.max(520, window.innerHeight - top - 8);
  1555. wrap.style.height = h + 'px';
  1556. if (cy) cy.resize();
  1557. }
  1558. function setupControls() {
  1559. applyTheme();
  1560. if (window.MutationObserver) {
  1561. var mo = new MutationObserver(applyTheme);
  1562. mo.observe(document.documentElement, {attributes: true, attributeFilter: ['theme', 'data-theme', 'color-scheme', 'class']});
  1563. if (document.body) {
  1564. mo.observe(document.body, {attributes: true, attributeFilter: ['theme', 'data-theme', 'color-scheme', 'class']});
  1565. }
  1566. }
  1567. var back = el('l2-back');
  1568. if (back) back.style.display = 'none';
  1569. el('l2-showterm').addEventListener('change', function () { showTerm = el('l2-showterm').checked; render(lastSnap); });
  1570. el('l2-onlyoff').addEventListener('change', function () {
  1571. onlyOff = el('l2-onlyoff').checked;
  1572. if (onlyOff && !showTerm) { showTerm = true; el('l2-showterm').checked = true; }
  1573. render(lastSnap);
  1574. });
  1575. el('l2-zin').addEventListener('click', function () { if (cy) cy.zoom({level: cy.zoom() * 1.25, renderedPosition: {x: cy.width() / 2, y: cy.height() / 2}}); });
  1576. el('l2-zout').addEventListener('click', function () { if (cy) cy.zoom({level: cy.zoom() / 1.25, renderedPosition: {x: cy.width() / 2, y: cy.height() / 2}}); });
  1577. el('l2-fit').addEventListener('click', function () { if (cy) cy.fit(cy.elements(), 50); });
  1578. el('l2-refresh-btn').addEventListener('click', function () { reload(true); });
  1579. window.addEventListener('resize', fitViewport);
  1580. var s = el('l2-search');
  1581. s.addEventListener('input', function () { doSearch(s.value); });
  1582. document.addEventListener('click', function (ev) {
  1583. if (!ev.target.closest('.l2-search-wrap')) el('l2-sug').style.display = 'none';
  1584. });
  1585. el('l2-ts').addEventListener('change', function () {
  1586. var v = el('l2-ts').value;
  1587. var u = '/zabbix.php?action=l2.topology.view';
  1588. if (v) u += '&ts=' + encodeURIComponent(v);
  1589. window.location = u;
  1590. });
  1591. el('l2-pause').addEventListener('click', function () {
  1592. paused = !paused;
  1593. el('l2-pause').classList.toggle('on', paused);
  1594. el('l2-pause').textContent = paused ? '▶' : '❚❚';
  1595. el('l2-pause').title = paused ? t('l2.resume', 'Resume') : t('l2.pause', 'Pause');
  1596. });
  1597. }
  1598. function reload(manual) {
  1599. if (!META.isLive) return;
  1600. fetch(META.snapshotUrl + '?t=' + Date.now(), {cache: 'no-store'})
  1601. .then(function (r) { return r.json(); })
  1602. .then(function (j) { if (j && j.nodes) { SNAP = j; INDEX = buildIndex(j); render(j); } })
  1603. .catch(function () {})
  1604. .then(function () { if (manual) resetCountdown(); });
  1605. }
  1606. function resetCountdown() { countdown = META.refreshSeconds || 300; }
  1607. function startTimer() {
  1608. if (!META.isLive) return;
  1609. resetCountdown();
  1610. timer = setInterval(function () {
  1611. if (paused) { el('l2-countdown').textContent = '⏸'; return; }
  1612. countdown--;
  1613. if (countdown <= 0) { countdown = META.refreshSeconds || 300; reload(false); }
  1614. var m = Math.floor(countdown / 60), s = countdown % 60;
  1615. el('l2-countdown').textContent = '↻ ' + m + ':' + (s < 10 ? '0' + s : s);
  1616. }, 1000);
  1617. }
  1618. /* ---------------- boot ---------------- */
  1619. function boot() {
  1620. setupControls();
  1621. fitViewport();
  1622. try {
  1623. var qs = new URLSearchParams(window.location.search);
  1624. var qg = qs.get('g');
  1625. if (qg) focusGroupLabel = qg;
  1626. } catch (e) {}
  1627. if (!SNAP || !SNAP.nodes) {
  1628. el('l2-cy').innerHTML = '<div class="l2-empty">' + t('l2.no_data', 'No data') + '</div>';
  1629. } else {
  1630. INDEX = buildIndex(SNAP);
  1631. render(SNAP);
  1632. }
  1633. setTimeout(fitViewport, 60);
  1634. if (META.isLive) startTimer();
  1635. else { el('l2-pause').disabled = true; el('l2-countdown').textContent = t('l2.snapshot', 'Snapshot'); }
  1636. }
  1637. if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
  1638. else boot();
  1639. })();