app.js 95 KB

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