app.js 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. /* ============================================================
  2. NetPulse landing - app.js v2
  3. Fondo canvas, tipografía grande, topología fiel a la app.
  4. ============================================================ */
  5. const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  6. const COLOR = {
  7. accent: '#22D3EE',
  8. tunnel: '#A78BFA',
  9. ok: '#34D399',
  10. warn: '#FBBF24',
  11. danger: '#F87171',
  12. info: '#60A5FA',
  13. };
  14. function getCssVar(name) {
  15. const s = getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim().split(' ');
  16. return `rgb(${s.join(' ')})`;
  17. }
  18. /* ---------- helpers ---------- */
  19. function easeOutCubic(x) { return 1 - Math.pow(1 - x, 3); }
  20. function easeOutExpo(x) { return x === 1 ? 1 : 1 - Math.pow(2, -10 * x); }
  21. function animateNumber(el, target, { decimals = 0, suffix = '', duration = 1200, format } = {}) {
  22. if (reduceMotion) {
  23. el.textContent = format ? format(target) : target.toFixed(decimals) + suffix;
  24. return;
  25. }
  26. const start = performance.now();
  27. function frame(now) {
  28. const p = Math.min(1, (now - start) / duration);
  29. const v = target * easeOutCubic(p);
  30. el.textContent = format ? format(v) : v.toFixed(decimals) + suffix;
  31. if (p < 1)
  32. requestAnimationFrame(frame);
  33. }
  34. requestAnimationFrame(frame);
  35. }
  36. function fmtLocale(n, decimals = 0) {
  37. return n.toLocaleString(CURRENT === 'en' ? 'en-US' : CURRENT, {
  38. minimumFractionDigits: decimals, maximumFractionDigits: decimals,
  39. });
  40. }
  41. function mkSvgEl(tag, attrs = {}, parent) {
  42. const e = document.createElementNS('http://www.w3.org/2000/svg', tag);
  43. Object.entries(attrs).forEach(([k, v]) => e.setAttribute(k, v));
  44. if (parent)
  45. parent.appendChild(e);
  46. return e;
  47. }
  48. /* ---------- fondo constelación viva (red con flujo de datos) ---------- */
  49. function mulberry32(seed) {
  50. let a = seed >>> 0;
  51. return function () {
  52. a |= 0;
  53. a = (a + 0x6D2B79F5) | 0;
  54. let t = Math.imul(a ^ (a >>> 15), 1 | a);
  55. t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
  56. return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  57. };
  58. }
  59. function initBackgroundCanvas() {
  60. const canvas = document.getElementById('bgCanvas');
  61. if (!canvas)
  62. return;
  63. const ctx = canvas.getContext('2d');
  64. const reduce = reduceMotion;
  65. const dpr = Math.min(window.devicePixelRatio || 1, 2);
  66. let w = 0, h = 0;
  67. let layers = [], bursts = [];
  68. let mx = -1e4, my = -1e4, tmx = -1e4, tmy = -1e4;
  69. const rand = mulberry32(0xC0FFEE);
  70. const alphaColor = (name, a) => getCssVar(name).replace(')', ` / ${a})`);
  71. const isLight = () => document.documentElement.classList.contains('light');
  72. const PALETTE = ['accent', 'tunnel', 'ok', 'info'];
  73. function buildLayout() {
  74. layers = [];
  75. bursts = [];
  76. const specs = [
  77. { depth: 0.5, count: 42, size: [1.6, 2.6], aMin: 0.22, aMax: 0.38, linkDist: 150, linkA: 0.10, gw: 0.02 },
  78. { depth: 0.75, count: 30, size: [2.2, 3.4], aMin: 0.35, aMax: 0.55, linkDist: 190, linkA: 0.14, gw: 0.08 },
  79. { depth: 1.0, count: 18, size: [3, 4.6], aMin: 0.5, aMax: 0.75, linkDist: 230, linkA: 0.18, gw: 0.15 },
  80. ];
  81. for (const s of specs) {
  82. const nodes = [];
  83. let guard = 0;
  84. while (nodes.length < s.count && guard++ < 2500) {
  85. const x = rand() * w;
  86. const y = rand() * h;
  87. const minD = 34 + rand() * 30;
  88. if (nodes.some((n) => Math.hypot(n.x - x, n.y - y) < minD))
  89. continue;
  90. nodes.push({
  91. x, y,
  92. r: s.size[0] + rand() * (s.size[1] - s.size[0]),
  93. a: s.aMin + rand() * (s.aMax - s.aMin),
  94. gw: rand() < s.gw,
  95. hue: Math.floor(rand() * PALETTE.length),
  96. ph: rand() * Math.PI * 2,
  97. wob: 1.5 + rand() * 2.5,
  98. });
  99. }
  100. const links = [];
  101. for (let i = 0; i < nodes.length; i++) {
  102. const dists = [];
  103. for (let j = 0; j < nodes.length; j++) {
  104. if (i === j)
  105. continue;
  106. dists.push([Math.hypot(nodes[i].x - nodes[j].x, nodes[i].y - nodes[j].y), j]);
  107. }
  108. dists.sort((a, b) => a[0] - b[0]);
  109. for (let k = 0; k < 2; k++) {
  110. const [d, j] = dists[k];
  111. if (d > s.linkDist || i > j)
  112. continue;
  113. links.push({ i, j, len: d, a: s.linkA * (0.6 + rand() * 0.8), ph: rand() * Math.PI * 2 });
  114. }
  115. }
  116. const packets = [];
  117. links.forEach((l, li) => {
  118. if (rand() < 0.42) {
  119. const n = l.len > 190 ? 2 : 1;
  120. for (let k = 0; k < n; k++)
  121. packets.push({ li, off: rand(), dur: 4 + rand() * 5, hue: Math.floor(rand() * PALETTE.length) });
  122. }
  123. });
  124. layers.push({ depth: s.depth, nodes, links, packets });
  125. }
  126. }
  127. function render(t) {
  128. ctx.clearRect(0, 0, w, h);
  129. for (const L of layers) {
  130. const k = L.depth;
  131. ctx.save();
  132. ctx.translate((mx - w / 2) * 0.05 * k, (my - h / 2) * 0.05 * k);
  133. // wobble sutil de cada nodo (vida, sin mover los enlaces)
  134. for (const n of L.nodes) {
  135. n.wx = n.x + Math.sin(t * 0.5 + n.ph) * n.wob;
  136. n.wy = n.y + Math.cos(t * 0.42 + n.ph) * n.wob;
  137. }
  138. // enlaces (respiran muy lentamente)
  139. ctx.lineWidth = 1;
  140. const lineMul = isLight() ? 0.45 : 1.25;
  141. for (const l of L.links) {
  142. const a = L.nodes[l.i], b = L.nodes[l.j];
  143. ctx.strokeStyle = alphaColor('text-secondary', l.a * lineMul * (0.65 + 0.35 * Math.sin(t * 0.4 + l.ph)));
  144. ctx.beginPath();
  145. ctx.moveTo(a.wx, a.wy);
  146. ctx.lineTo(b.wx, b.wy);
  147. ctx.stroke();
  148. }
  149. // nodos
  150. const nodeMul = isLight() ? 0.5 : 1;
  151. for (const n of L.nodes) {
  152. ctx.fillStyle = alphaColor(PALETTE[n.hue], n.a * nodeMul);
  153. ctx.beginPath();
  154. ctx.arc(n.wx, n.wy, n.r, 0, Math.PI * 2);
  155. ctx.fill();
  156. if (n.gw) {
  157. ctx.strokeStyle = alphaColor(PALETTE[n.hue], n.a * nodeMul * 0.5);
  158. ctx.lineWidth = 1;
  159. ctx.beginPath();
  160. ctx.arc(n.wx, n.wy, n.r + 3 + Math.sin(t * 1.2 + n.ph) * 1.2, 0, Math.PI * 2);
  161. ctx.stroke();
  162. }
  163. }
  164. // paquetes de datos viajando por los enlaces
  165. for (const p of L.packets) {
  166. const l = L.links[p.li];
  167. const a = L.nodes[l.i], b = L.nodes[l.j];
  168. const frac = (p.off + t / p.dur) % 1;
  169. const col = PALETTE[p.hue];
  170. ctx.save();
  171. ctx.shadowColor = getCssVar(col);
  172. ctx.shadowBlur = 8;
  173. ctx.fillStyle = alphaColor(col, 0.9);
  174. ctx.beginPath();
  175. ctx.arc(a.wx + (b.wx - a.wx) * frac, a.wy + (b.wy - a.wy) * frac, 1.8, 0, Math.PI * 2);
  176. ctx.fill();
  177. ctx.restore();
  178. }
  179. // ráfagas ocasionales (evento que recorre un enlace)
  180. if (L.depth >= 0.7) {
  181. for (const b of bursts) {
  182. if (b.layer !== L.depth)
  183. continue;
  184. const l = L.links[b.li];
  185. if (!l)
  186. continue;
  187. const a = L.nodes[l.i], bb = L.nodes[l.j];
  188. const prog = (t - b.t0) / b.dur;
  189. if (prog >= 0 && prog <= 1) {
  190. ctx.save();
  191. ctx.shadowColor = getCssVar('accent');
  192. ctx.shadowBlur = 14;
  193. ctx.fillStyle = alphaColor('accent', 0.95 * (1 - prog));
  194. ctx.beginPath();
  195. ctx.arc(a.wx + (bb.wx - a.wx) * prog, a.wy + (bb.wy - a.wy) * prog, 2.6 * (1 - prog * 0.5), 0, Math.PI * 2);
  196. ctx.fill();
  197. ctx.restore();
  198. }
  199. }
  200. }
  201. ctx.restore();
  202. }
  203. bursts = bursts.filter((b) => t - b.t0 < b.dur);
  204. }
  205. function maybeBurst(t) {
  206. const L = layers[1] || layers[layers.length - 1];
  207. if (!L || L.links.length === 0)
  208. return;
  209. bursts.push({ layer: L.depth, li: Math.floor(rand() * L.links.length), t0: t, dur: 1.6 });
  210. }
  211. function resize() {
  212. w = window.innerWidth;
  213. h = window.innerHeight;
  214. canvas.width = Math.round(w * dpr);
  215. canvas.height = Math.round(h * dpr);
  216. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  217. buildLayout();
  218. if (reduce)
  219. render(0);
  220. }
  221. resize();
  222. window.addEventListener('resize', resize);
  223. document.addEventListener('mousemove', (e) => { tmx = e.clientX; tmy = e.clientY; }, { passive: true });
  224. document.addEventListener('touchmove', (e) => { if (e.touches[0]) {
  225. tmx = e.touches[0].clientX;
  226. tmy = e.touches[0].clientY;
  227. } }, { passive: true });
  228. if (reduce)
  229. return;
  230. let nextBurst = 3 + rand() * 4;
  231. function loop(now) {
  232. const t = now / 1000;
  233. mx += (tmx - mx) * 0.06;
  234. my += (tmy - my) * 0.06;
  235. if (t > nextBurst) {
  236. maybeBurst(t);
  237. nextBurst = t + 5 + rand() * 6;
  238. }
  239. render(t);
  240. requestAnimationFrame(loop);
  241. }
  242. requestAnimationFrame(loop);
  243. }
  244. /* ---------- count-up hero ---------- */
  245. function heroCountUps() {
  246. document.querySelectorAll('#heroStrip [data-count]').forEach(el => {
  247. const target = parseFloat(el.dataset.count);
  248. const decimals = parseInt(el.dataset.decimals || '0', 10);
  249. const suffix = el.dataset.suffix || '';
  250. animateNumber(el, target, { decimals, suffix, duration: 1400 });
  251. });
  252. }
  253. /* ---------- ticker ---------- */
  254. function renderTicker() {
  255. const el = document.getElementById('ticker');
  256. if (!el)
  257. return;
  258. const items = [
  259. `<span><i class="dot" style="background:rgb(var(--ok))"></i><i>${t('strip.health')}</i>&nbsp;<i class="font-mono">92/100</i></span>`,
  260. `<span><i class="dot" style="background:rgb(var(--accent))"></i><i>${t('strip.down')}</i>&nbsp;<i class="font-mono">84.2 Mbps</i></span>`,
  261. `<span><i class="dot" style="background:rgb(var(--tunnel))"></i><i>${t('strip.up')}</i>&nbsp;<i class="font-mono">12.6 Mbps</i></span>`,
  262. `<span><i class="dot" style="background:rgb(var(--info))"></i><i>${t('strip.latency')}</i>&nbsp;<i class="font-mono">8 ms</i></span>`,
  263. `<span><i class="dot" style="background:rgb(var(--text-secondary))"></i><i>${t('strip.devices')}</i>&nbsp;<i class="font-mono">65</i></span>`,
  264. `<span><i class="dot" style="background:rgb(var(--danger))"></i><i>AdGuard</i>&nbsp;<i class="font-mono">60/65 ${t('adguard.clients')}</i></span>`,
  265. `<span><i class="dot" style="background:rgb(var(--warn))"></i><i>DNS</i>&nbsp;<i class="font-mono">14 ms</i></span>`,
  266. `<span><i class="dot" style="background:rgb(var(--ok))"></i><i>WireGuard</i>&nbsp;<i class="font-mono">peer phone · ${t('alerts.ago')} 2 min</i></span>`,
  267. ];
  268. el.innerHTML = items.join('') + items.join('');
  269. }
  270. /* ---------- stage 0: health ring + advertencias + ancho de banda ---------- */
  271. let ringPlayed = false;
  272. function playRing() {
  273. if (ringPlayed)
  274. return;
  275. ringPlayed = true;
  276. const arc = document.getElementById('ringArc');
  277. const num = document.getElementById('ringNum');
  278. const C = 590.6;
  279. const score = DEMO.score;
  280. animateNumber(document.getElementById('hDown'), DEMO_WAN.downMbps, { decimals: 1, duration: 1400 });
  281. animateNumber(document.getElementById('hUp'), DEMO_WAN.upMbps, { decimals: 1, duration: 1400 });
  282. animateNumber(document.getElementById('hLat'), DEMO_WAN.latencyMs, { duration: 1400 });
  283. if (reduceMotion) {
  284. arc.style.strokeDashoffset = String(C * (1 - score / 100));
  285. num.textContent = String(score);
  286. return;
  287. }
  288. const dur = 1300;
  289. const start = performance.now();
  290. function frame(now) {
  291. const p = Math.min(1, (now - start) / dur);
  292. const e = easeOutCubic(p);
  293. const v = score * e;
  294. num.textContent = String(Math.round(v));
  295. arc.style.strokeDashoffset = String(C * (1 - v / 100));
  296. if (p < 1)
  297. requestAnimationFrame(frame);
  298. }
  299. requestAnimationFrame(frame);
  300. }
  301. /* ---------- stage 1: tráfico WAN por rango (1h/24h/7d/30d) ---------- */
  302. let trafficPlayed = false;
  303. let trafficTimer = null;
  304. let trafficRange = '24h';
  305. const TRAFFIC_TICKS = { '1h': 5, '24h': 6, '7d': 7, '30d': 5 };
  306. const NS_T = 'http://www.w3.org/2000/svg';
  307. function renderTrafficChart(animate) {
  308. const data = DEMO_TRAFFIC[trafficRange];
  309. if (!data || data.length < 2)
  310. return;
  311. const W = 480, H = 200, padL = 8, padR = 8, padT = 14, padB = 26;
  312. const max = Math.max(1, ...data.map((p) => Math.max(p.down, p.up))) * 1.15;
  313. const stepX = (W - padL - padR) / (data.length - 1);
  314. const X = (i) => padL + i * stepX;
  315. const Y = (v) => padT + (H - padT - padB) * (1 - v / max);
  316. const path = (key) => data.map((p, i) => `${i ? 'L' : 'M'}${X(i).toFixed(1)} ${Y(p[key]).toFixed(1)}`).join(' ');
  317. const down = path('down'), up = path('up');
  318. const lineDown = document.getElementById('lineDown');
  319. const lineUp = document.getElementById('lineUp');
  320. const areaDown = document.getElementById('areaDown');
  321. const areaUp = document.getElementById('areaUp');
  322. const x0 = X(0).toFixed(1), xN = X(data.length - 1).toFixed(1);
  323. lineDown.setAttribute('d', down);
  324. lineUp.setAttribute('d', up);
  325. areaDown.setAttribute('d', `${down} L${xN} ${H} L${x0} ${H} Z`);
  326. areaUp.setAttribute('d', `${up} L${xN} ${H} L${x0} ${H} Z`);
  327. // rejilla horizontal
  328. const grid = document.getElementById('trafficGrid');
  329. grid.innerHTML = '';
  330. for (let g = 1; g <= 3; g++) {
  331. const gy = padT + (H - padT - padB) * (g / 4);
  332. const el = document.createElementNS(NS_T, 'line');
  333. el.setAttribute('x1', String(padL));
  334. el.setAttribute('x2', String(W - padR));
  335. el.setAttribute('y1', String(gy));
  336. el.setAttribute('y2', String(gy));
  337. el.setAttribute('stroke', 'rgb(var(--border))');
  338. el.setAttribute('stroke-dasharray', '3 6');
  339. el.setAttribute('opacity', '0.5');
  340. grid.appendChild(el);
  341. }
  342. // ticks del eje X
  343. const ticks = document.getElementById('trafficXTicks');
  344. ticks.innerHTML = '';
  345. const n = TRAFFIC_TICKS[trafficRange] || 5;
  346. for (let k = 0; k < n; k++) {
  347. const idx = Math.round((k * (data.length - 1)) / (n - 1));
  348. const tx = document.createElementNS(NS_T, 'text');
  349. tx.setAttribute('x', String(X(idx)));
  350. tx.setAttribute('y', String(H - 8));
  351. tx.setAttribute('text-anchor', 'middle');
  352. tx.textContent = data[idx].t;
  353. ticks.appendChild(tx);
  354. }
  355. if (animate) {
  356. const Ld = lineDown.getTotalLength();
  357. const Lu = lineUp.getTotalLength();
  358. lineDown.style.strokeDasharray = String(Ld);
  359. lineDown.style.strokeDashoffset = String(Ld);
  360. lineUp.style.strokeDasharray = String(Lu);
  361. lineUp.style.strokeDashoffset = String(Lu);
  362. const start = performance.now(), dur = 1400;
  363. function frame(now) {
  364. const p = Math.min(1, (now - start) / dur);
  365. const e = easeOutCubic(p);
  366. lineDown.style.strokeDashoffset = String(Ld * (1 - e));
  367. lineUp.style.strokeDashoffset = String(Lu * (1 - e));
  368. areaDown.setAttribute('opacity', String(e * 0.9));
  369. areaUp.setAttribute('opacity', String(e * 0.8));
  370. if (p < 1)
  371. requestAnimationFrame(frame);
  372. }
  373. requestAnimationFrame(frame);
  374. }
  375. else {
  376. lineDown.style.strokeDasharray = '';
  377. lineDown.style.strokeDashoffset = '';
  378. lineUp.style.strokeDasharray = '';
  379. lineUp.style.strokeDashoffset = '';
  380. areaDown.setAttribute('opacity', '0.9');
  381. areaUp.setAttribute('opacity', '0.8');
  382. }
  383. }
  384. function renderWanFooter() {
  385. const w = DEMO_WAN;
  386. const set = (id, v) => { const el = document.getElementById(id); if (el)
  387. el.textContent = v; };
  388. set('wanPeak', `${w.peakTodayMbps} Mbps ↓`);
  389. set('wanAvg', `${w.avgDownMbps} Mbps ↓`);
  390. set('wanTotal', w.total24h);
  391. set('wanLoss', `${w.lossPct} %`);
  392. }
  393. function playTraffic() {
  394. if (trafficPlayed)
  395. return;
  396. trafficPlayed = true;
  397. renderTrafficChart(true);
  398. renderWanFooter();
  399. animateNumber(document.getElementById('wanDown'), DEMO_WAN.downMbps, { decimals: 1, duration: 1400 });
  400. animateNumber(document.getElementById('wanUp'), DEMO_WAN.upMbps, { decimals: 1, duration: 1400 });
  401. animateNumber(document.getElementById('wanLat'), DEMO_WAN.latencyMs, { duration: 1400 });
  402. if (reduceMotion)
  403. return;
  404. trafficTimer = setInterval(() => {
  405. const downEl = document.getElementById('wanDown');
  406. if (!downEl.isConnected)
  407. return;
  408. const d = Math.max(55, DEMO_WAN.downMbps + (Math.random() - 0.5) * 7);
  409. const u = Math.max(9, DEMO_WAN.upMbps + (Math.random() - 0.5) * 2.5);
  410. downEl.textContent = d.toFixed(1);
  411. document.getElementById('wanUp').textContent = u.toFixed(1);
  412. }, 2600);
  413. }
  414. function setTrafficRange(r) {
  415. if (trafficRange === r)
  416. return;
  417. trafficRange = r;
  418. document.querySelectorAll('#trafficRanges button').forEach((b) => b.classList.toggle('on', b.dataset.range === r));
  419. renderTrafficChart(false);
  420. }
  421. /* ---------- stage 2: topologia fiel a la app (model.ts + TopologyMap.tsx) ---------- */
  422. let topoBuilt = false;
  423. let routersBuilt = false;
  424. let routersPlayed = false;
  425. /* ===== datos demo canonicos (demo-canon.json, D65-1) ===== */
  426. const DEMO_WAN = { "plan": "600/600 Mbps", "downMbps": 84.2, "upMbps": 12.6, "latencyMs": 8, "lossPct": 0, "publicIp": "84.122.x.x", "isp": "Digi", "peakTodayMbps": 412, "peakTodayTime": "21:14", "avgDownMbps": 61, "total24h": "1,32 TB" };
  427. /* tráfico WAN por rango (mock.ts, canon) y AdGuard Home (demo-canon.json) */
  428. const DEMO_TRAFFIC = { "1h": [{ "t": "21:30", "down": 68, "up": 9 }, { "t": "21:33", "down": 74, "up": 10 }, { "t": "21:36", "down": 81, "up": 11 }, { "t": "21:39", "down": 92, "up": 12 }, { "t": "21:42", "down": 88, "up": 10 }, { "t": "21:45", "down": 96, "up": 13 }, { "t": "21:48", "down": 104, "up": 14 }, { "t": "21:51", "down": 98, "up": 12 }, { "t": "21:54", "down": 90, "up": 11 }, { "t": "21:57", "down": 86, "up": 10 }, { "t": "22:00", "down": 82, "up": 11 }, { "t": "22:03", "down": 78, "up": 12 }, { "t": "22:06", "down": 84, "up": 13 }, { "t": "22:09", "down": 91, "up": 14 }, { "t": "22:12", "down": 88, "up": 12 }, { "t": "22:15", "down": 84, "up": 11 }, { "t": "22:18", "down": 80, "up": 10 }, { "t": "22:21", "down": 83, "up": 12 }, { "t": "22:24", "down": 86, "up": 13 }, { "t": "22:27", "down": 84, "up": 12.6 }], "24h": [{ "t": "00", "down": 42, "up": 8 }, { "t": "01", "down": 28, "up": 6 }, { "t": "02", "down": 15, "up": 5 }, { "t": "03", "down": 9, "up": 4 }, { "t": "04", "down": 7, "up": 4 }, { "t": "05", "down": 8, "up": 5 }, { "t": "06", "down": 14, "up": 6 }, { "t": "07", "down": 32, "up": 9 }, { "t": "08", "down": 58, "up": 14 }, { "t": "09", "down": 74, "up": 18 }, { "t": "10", "down": 88, "up": 21 }, { "t": "11", "down": 96, "up": 24 }, { "t": "12", "down": 112, "up": 26 }, { "t": "13", "down": 124, "up": 28 }, { "t": "14", "down": 118, "up": 25 }, { "t": "15", "down": 132, "up": 27 }, { "t": "16", "down": 148, "up": 30 }, { "t": "17", "down": 176, "up": 34 }, { "t": "18", "down": 224, "up": 42 }, { "t": "19", "down": 298, "up": 55 }, { "t": "20", "down": 356, "up": 71 }, { "t": "21", "down": 412, "up": 96 }, { "t": "22", "down": 284, "up": 48 }, { "t": "23", "down": 122, "up": 21 }], "7d": [{ "t": "Mon", "down": 61, "up": 12 }, { "t": "Tue", "down": 58, "up": 11 }, { "t": "Wed", "down": 64, "up": 13 }, { "t": "Thu", "down": 71, "up": 15 }, { "t": "Fri", "down": 88, "up": 19 }, { "t": "Sat", "down": 96, "up": 22 }, { "t": "Sun", "down": 84, "up": 18 }], "30d": [{ "t": "1", "down": 54, "up": 10 }, { "t": "4", "down": 58, "up": 11 }, { "t": "7", "down": 62, "up": 12 }, { "t": "10", "down": 57, "up": 11 }, { "t": "13", "down": 66, "up": 13 }, { "t": "16", "down": 72, "up": 15 }, { "t": "19", "down": 68, "up": 14 }, { "t": "22", "down": 75, "up": 16 }, { "t": "25", "down": 81, "up": 18 }, { "t": "28", "down": 78, "up": 17 }, { "t": "30", "down": 84, "up": 19 }] };
  429. const DEMO_ADGUARD = { "blockedPct": 18.6, "blocked24h": 15687, "queries24h": 84312, "trackersBlocked": 9204, "dnsLatencyMs": 14, "clientsUsing": 60, "clientsTotal": 65, "topBlocked": [{ "domain": "graph.facebook.com", "count": 1204 }, { "domain": "adservice.google.com", "count": 986 }, { "domain": "metrics.icloud.com", "count": 731 }] };
  430. const DEMO_WG = {
  431. interface: 'wg0', subnet: '10.0.0.1/24', status: 'active',
  432. peers: [
  433. { "id": "pixel-8-pro", "name": "Pixel 8 Pro", "type": "movil", "tunnelIp": "10.0.0.2", "active": true, "lastHandshake": "hace 38 s", "rx": "1,2 GB", "tx": "214 MB" },
  434. { "id": "macbook-air", "name": "MacBook Air", "type": "portatil", "tunnelIp": "10.0.0.3", "active": true, "lastHandshake": "hace 1 min", "rx": "640 MB", "tx": "88 MB" },
  435. { "id": "ipad-air", "name": "iPad Air", "type": "tablet", "tunnelIp": "10.0.0.4", "active": false, "lastHandshake": "hace 2 días", "rx": "3,1 GB", "tx": "402 MB" },
  436. { "id": "portatil-trabajo", "name": "Portátil trabajo", "type": "portatil", "tunnelIp": "10.0.0.5", "active": false, "lastHandshake": "hace 6 h", "rx": "812 MB", "tx": "121 MB" },
  437. { "id": "casa-familia", "name": "Casa familia", "type": "sitio", "tunnelIp": "10.0.0.6", "active": false, "lastHandshake": "hace 9 días", "rx": "12 GB", "tx": "4,2 GB" },
  438. ],
  439. };
  440. const DEMO_DISTRIBUTION = [
  441. { "id": "dist-flint2-lan3", "kind": "inferred", "routerId": "flint2", "port": "lan3", "macCount": 8 },
  442. { "id": "dist-pve", "kind": "hypervisor", "routerId": "flint2", "port": "lan5", "macCount": 11, "hostDeviceId": "pve", "name": "Proxmox pve" },
  443. { "id": "dist-living-lan3", "kind": "managed", "routerId": "living", "port": "lan3", "macCount": 4, "name": "GS308E", "ip": "192.168.8.13", "mac": "28:C6:8E:1D:90:44", "lldp": { "chassis": "GS308E", "mgmt": "192.168.8.13", "caps": "Bridge", "portDesc": "ge5" } },
  444. ];
  445. const DEMO_DEVICES = [
  446. { "id": "imac-salon", "name": "iMac Salón", "type": "ordenador", "manufacturer": "Apple", "ip": "192.168.8.21", "mac": "A4:83:E7:21:0B:3C", "routerId": "living", "band": "5 GHz", "signalDbm": -48, "trafficMbps": 32.4, "online": true },
  447. { "id": "tv-samsung", "name": "TV Samsung", "type": "tv", "manufacturer": "Samsung", "ip": "192.168.8.34", "mac": "8C:EA:48:5D:2F:91", "routerId": "living", "band": "5 GHz", "signalDbm": -52, "trafficMbps": 18.1, "online": true },
  448. { "id": "pixel-8-pro", "name": "Pixel 8 Pro", "type": "movil", "manufacturer": "Google", "ip": "192.168.8.45", "mac": "F2:6D:19:A8:44:C2", "routerId": "flint2", "band": "5 GHz", "signalDbm": -41, "trafficMbps": 6.2, "online": true },
  449. { "id": "macbook-air", "name": "MacBook Air", "type": "portatil", "manufacturer": "Apple", "ip": "192.168.8.23", "mac": "3C:22:FB:71:9E:05", "routerId": "estudio", "band": "5 GHz", "signalDbm": -45, "trafficMbps": 4.8, "online": true },
  450. { "id": "ps5", "name": "PS5", "type": "consola", "manufacturer": "Sony", "ip": "192.168.8.31", "mac": "78:C8:81:0A:6B:D4", "routerId": "living", "band": "cable", "signalDbm": null, "trafficMbps": 12.7, "online": true, "port": "lan1" },
  451. { "id": "robot-aspirador", "name": "Robot aspirador", "type": "iot", "manufacturer": "Roborock", "ip": "192.168.8.61", "mac": "B0:4A:39:2E:77:10", "routerId": "patio", "band": "2.4 GHz", "signalDbm": -67, "trafficMbps": 0.02, "online": true },
  452. { "id": "camara-porche", "name": "Cámara porche", "type": "camara", "manufacturer": "Reolink", "ip": "192.168.8.71", "mac": "EC:71:DB:44:12:8A", "routerId": "patio", "band": "2.4 GHz", "signalDbm": -72, "trafficMbps": 1.1, "online": true },
  453. { "id": "nest-mini", "name": "Nest Mini", "type": "altavoz", "manufacturer": "Google", "ip": "192.168.8.52", "mac": "1A:2B:3C:4D:5E:6F", "routerId": "estudio", "band": "2.4 GHz", "signalDbm": -55, "trafficMbps": 0.4, "online": true },
  454. { "id": "nas-synology", "name": "NAS Synology", "type": "servidor", "manufacturer": "Synology", "ip": "192.168.8.10", "mac": "00:11:32:9C:51:B7", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 2.3, "online": true, "port": "lan4" },
  455. { "id": "galaxy-tab-s9", "name": "Galaxy Tab S9", "type": "tablet", "manufacturer": "Samsung", "ip": "192.168.8.48", "mac": "D6:91:2F:07:B3:55", "routerId": "living", "band": "5 GHz", "signalDbm": -50, "trafficMbps": 1.8, "online": true },
  456. { "id": "iphone-ana", "name": "iPhone de Ana", "type": "movil", "manufacturer": "Apple", "ip": "192.168.8.44", "mac": "F4:D4:88:19:C2:71", "routerId": "flint2", "band": "5 GHz", "signalDbm": -46, "trafficMbps": 2.1, "online": true },
  457. { "id": "macbook-pro", "name": "MacBook Pro de Marc", "type": "portatil", "manufacturer": "Apple", "ip": "192.168.8.26", "mac": "F0:18:98:5A:11:E9", "routerId": "flint2", "band": "5 GHz", "signalDbm": -44, "trafficMbps": 8.6, "online": true },
  458. { "id": "pc-sobremesa", "name": "PC de sobremesa", "type": "ordenador", "manufacturer": "ASUSTeK", "ip": "192.168.8.11", "mac": "04:D4:C4:8B:30:A7", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 21.3, "online": true, "attachTo": "dist-flint2-lan3" },
  459. { "id": "raspberry-pi", "name": "Raspberry Pi 4", "type": "servidor", "manufacturer": "Raspberry Pi", "ip": "192.168.8.12", "mac": "DC:A6:32:4F:77:02", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.8, "online": true, "attachTo": "dist-flint2-lan3" },
  460. { "id": "timbre-nest", "name": "Timbre Nest", "type": "camara", "manufacturer": "Google", "ip": "192.168.8.72", "mac": "F4:F5:D8:66:01:B8", "routerId": "flint2", "band": "2.4 GHz", "signalDbm": -58, "trafficMbps": 0.6, "online": true },
  461. { "id": "enchufe-lavadora", "name": "Enchufe lavadora", "type": "iot", "manufacturer": "TP-Link", "ip": "192.168.8.81", "mac": "50:C7:BF:22:E1:9C", "routerId": "flint2", "band": "2.4 GHz", "signalDbm": -62, "trafficMbps": 0.01, "online": true },
  462. { "id": "pixel-7", "name": "Pixel 7", "type": "movil", "manufacturer": "Google", "ip": "192.168.8.46", "mac": "3C:5A:B4:08:D7:5E", "routerId": "flint2", "band": "5 GHz", "signalDbm": -49, "trafficMbps": 1.4, "online": true },
  463. { "id": "ipad-air", "name": "iPad Air", "type": "tablet", "manufacturer": "Apple", "ip": "192.168.8.47", "mac": "8C:85:90:2F:B4:11", "routerId": "flint2", "band": "5 GHz", "signalDbm": -54, "trafficMbps": 0, "online": false },
  464. { "id": "portatil-trabajo", "name": "Portátil trabajo", "type": "portatil", "manufacturer": "Lenovo", "ip": "192.168.8.27", "mac": "54:EE:75:9A:03:F1", "routerId": "flint2", "band": "5 GHz", "signalDbm": -50, "trafficMbps": 0, "online": false },
  465. { "id": "kindle", "name": "Kindle Paperwhite", "type": "desconocido", "manufacturer": "Amazon", "ip": "192.168.8.49", "mac": "44:65:0D:71:28:C3", "routerId": "flint2", "band": "2.4 GHz", "signalDbm": -58, "trafficMbps": 0, "online": false },
  466. { "id": "bombilla-1", "name": "Bombilla salón 1", "type": "iot", "manufacturer": "Ikea Trådfri", "ip": "192.168.8.90", "mac": "CC:86:EC:10:04:21", "routerId": "living", "band": "2.4 GHz", "signalDbm": -58, "trafficMbps": 0, "online": true },
  467. { "id": "bombilla-2", "name": "Bombilla salón 2", "type": "iot", "manufacturer": "Ikea Trådfri", "ip": "192.168.8.91", "mac": "CC:86:EC:10:04:22", "routerId": "living", "band": "2.4 GHz", "signalDbm": -59, "trafficMbps": 0, "online": true },
  468. { "id": "bombilla-3", "name": "Bombilla lámpara pie", "type": "iot", "manufacturer": "Ikea Trådfri", "ip": "192.168.8.92", "mac": "CC:86:EC:10:04:23", "routerId": "living", "band": "2.4 GHz", "signalDbm": -61, "trafficMbps": 0, "online": true },
  469. { "id": "bombilla-4", "name": "Bombilla entrada", "type": "iot", "manufacturer": "Ikea Trådfri", "ip": "192.168.8.93", "mac": "CC:86:EC:10:04:24", "routerId": "living", "band": "2.4 GHz", "signalDbm": -64, "trafficMbps": 0, "online": true },
  470. { "id": "bombilla-5", "name": "Bombilla pasillo", "type": "iot", "manufacturer": "Ikea Trådfri", "ip": "192.168.8.94", "mac": "CC:86:EC:10:04:25", "routerId": "living", "band": "2.4 GHz", "signalDbm": -66, "trafficMbps": 0, "online": true },
  471. { "id": "bombilla-6", "name": "Bombilla cocina", "type": "iot", "manufacturer": "Ikea Trådfri", "ip": "192.168.8.95", "mac": "CC:86:EC:10:04:26", "routerId": "living", "band": "2.4 GHz", "signalDbm": -60, "trafficMbps": 0, "online": true },
  472. { "id": "chromecast", "name": "Chromecast HD", "type": "tv", "manufacturer": "Google", "ip": "192.168.8.36", "mac": "54:60:09:E3:5B:0A", "routerId": "living", "band": "5 GHz", "signalDbm": -54, "trafficMbps": 3.9, "online": true },
  473. { "id": "homepod-mini", "name": "HomePod mini", "type": "altavoz", "manufacturer": "Apple", "ip": "192.168.8.53", "mac": "F0:D1:A9:3E:77:5C", "routerId": "living", "band": "5 GHz", "signalDbm": -47, "trafficMbps": 0.3, "online": true },
  474. { "id": "galaxy-s23", "name": "Galaxy S23", "type": "movil", "manufacturer": "Samsung", "ip": "192.168.8.42", "mac": "5C:0A:5B:88:1D:E4", "routerId": "living", "band": "5 GHz", "signalDbm": -51, "trafficMbps": 0.9, "online": true },
  475. { "id": "echo-dot", "name": "Echo Dot", "type": "altavoz", "manufacturer": "Amazon", "ip": "192.168.8.54", "mac": "74:C2:46:19:F0:6B", "routerId": "living", "band": "2.4 GHz", "signalDbm": -56, "trafficMbps": 0.2, "online": true },
  476. { "id": "nintendo-switch", "name": "Nintendo Switch", "type": "consola", "manufacturer": "Nintendo", "ip": "192.168.8.33", "mac": "58:BD:A3:4C:E2:09", "routerId": "living", "band": "5 GHz", "signalDbm": -53, "trafficMbps": 0.1, "online": true },
  477. { "id": "portatil-invitado", "name": "Portátil invitado", "type": "portatil", "manufacturer": "Desconocido", "ip": "192.168.8.29", "mac": "A2:7E:9C:41:0B:6D", "routerId": "living", "band": "5 GHz", "signalDbm": -58, "trafficMbps": 0.7, "online": true },
  478. { "id": "portatil-antiguo", "name": "Portátil antiguo", "type": "portatil", "manufacturer": "HP", "ip": "192.168.8.28", "mac": "3C:52:82:5D:90:17", "routerId": "living", "band": "2.4 GHz", "signalDbm": -62, "trafficMbps": 0, "online": false },
  479. { "id": "mac-mini", "name": "Mac mini", "type": "ordenador", "manufacturer": "Apple", "ip": "192.168.8.22", "mac": "A4:83:E7:66:2C:98", "routerId": "estudio", "band": "cable", "signalDbm": null, "trafficMbps": 1.9, "online": true },
  480. { "id": "enchufe-ventilador", "name": "Enchufe ventilador", "type": "iot", "manufacturer": "TP-Link", "ip": "192.168.8.82", "mac": "9C:53:22:B1:4E:70", "routerId": "estudio", "band": "2.4 GHz", "signalDbm": -59, "trafficMbps": 0.01, "online": true },
  481. { "id": "ipad-pro", "name": "iPad Pro", "type": "tablet", "manufacturer": "Apple", "ip": "192.168.8.51", "mac": "F0:18:98:91:5A:2B", "routerId": "estudio", "band": "5 GHz", "signalDbm": -49, "trafficMbps": 0.8, "online": true },
  482. { "id": "hue-hub", "name": "Hub Philips Hue", "type": "iot", "manufacturer": "Signify", "ip": "192.168.8.15", "mac": "00:17:88:2A:91:CE", "routerId": "estudio", "band": "cable", "signalDbm": null, "trafficMbps": 0.02, "online": true },
  483. { "id": "sonos-one", "name": "Sonos One", "type": "altavoz", "manufacturer": "Sonos", "ip": "192.168.8.55", "mac": "48:A6:B8:14:72:E0", "routerId": "estudio", "band": "2.4 GHz", "signalDbm": -57, "trafficMbps": 0.5, "online": true },
  484. { "id": "iphone-trabajo", "name": "iPhone de trabajo", "type": "movil", "manufacturer": "Apple", "ip": "192.168.8.50", "mac": "8C:85:90:47:C1:93", "routerId": "estudio", "band": "5 GHz", "signalDbm": -47, "trafficMbps": 0.3, "online": true },
  485. { "id": "macbook-viejo", "name": "MacBook viejo", "type": "portatil", "manufacturer": "Apple", "ip": "192.168.8.25", "mac": "3C:22:FB:0E:66:A1", "routerId": "estudio", "band": "2.4 GHz", "signalDbm": -60, "trafficMbps": 0, "online": false },
  486. { "id": "camara-jardin", "name": "Cámara jardín", "type": "camara", "manufacturer": "Reolink", "ip": "192.168.8.73", "mac": "EC:71:DB:44:12:9B", "routerId": "patio", "band": "2.4 GHz", "signalDbm": -74, "trafficMbps": 1.4, "online": true },
  487. { "id": "sensor-riego", "name": "Sensor de riego", "type": "iot", "manufacturer": "Tuya", "ip": "192.168.8.89", "mac": "D8:1F:12:5B:08:44", "routerId": "patio", "band": "2.4 GHz", "signalDbm": -71, "trafficMbps": 0.01, "online": true },
  488. { "id": "enchufe-calefactor", "name": "Enchufe calefactor", "type": "iot", "manufacturer": "TP-Link", "ip": "192.168.8.80", "mac": "50:C7:BF:31:7A:05", "routerId": "patio", "band": "2.4 GHz", "signalDbm": -75, "trafficMbps": 0.02, "online": true },
  489. { "id": "camara-garaje", "name": "Cámara garaje", "type": "camara", "manufacturer": "Reolink", "ip": "192.168.8.74", "mac": "EC:71:DB:44:13:02", "routerId": "patio", "band": "2.4 GHz", "signalDbm": -78, "trafficMbps": 0, "online": false },
  490. { "id": "switch-netgear", "name": "Switch GS308E", "type": "switch", "manufacturer": "Netgear", "ip": "192.168.8.13", "mac": "28:C6:8E:1D:90:44", "routerId": "living", "band": "cable", "signalDbm": null, "trafficMbps": 0.02, "online": true, "port": "lan3", "attachTo": "living", "lldp": { "chassis": "GS308E", "mgmt": "192.168.8.13", "caps": "Bridge", "portDesc": "ge5" } },
  491. { "id": "xbox-series-s", "name": "Xbox Series S", "type": "consola", "manufacturer": "Microsoft", "ip": "192.168.8.35", "mac": "7C:ED:8D:4A:11:22", "routerId": "living", "band": "cable", "signalDbm": null, "trafficMbps": 9.8, "online": true, "attachTo": "dist-living-lan3" },
  492. { "id": "apple-tv-4k", "name": "Apple TV 4K", "type": "tv", "manufacturer": "Apple", "ip": "192.168.8.36", "mac": "F0:18:98:2B:33:44", "routerId": "living", "band": "cable", "signalDbm": null, "trafficMbps": 15.2, "online": true, "attachTo": "dist-living-lan3" },
  493. { "id": "receptor-denon", "name": "Receptor Denon", "type": "altavoz", "manufacturer": "Denon", "ip": "192.168.8.37", "mac": "00:05:CD:55:66:77", "routerId": "living", "band": "cable", "signalDbm": null, "trafficMbps": 0.6, "online": true, "attachTo": "dist-living-lan3" },
  494. { "id": "pve", "name": "Proxmox pve", "type": "servidor", "manufacturer": "Supermicro", "ip": "192.168.8.5", "mac": "3C:52:82:10:20:30", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 12.3, "online": true, "port": "lan5" },
  495. { "id": "ct-pihole", "name": "Pi-hole", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.41", "mac": "BC:24:11:00:20:10", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 6.1, "online": true, "attachTo": "pve" },
  496. { "id": "ct-home-assistant", "name": "Home Assistant", "type": "iot", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.42", "mac": "BC:24:11:00:21:11", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 4.2, "online": true, "attachTo": "pve" },
  497. { "id": "ct-nextcloud", "name": "Nextcloud", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.43", "mac": "BC:24:11:00:22:12", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 7.8, "online": true, "attachTo": "pve" },
  498. { "id": "ct-jellyfin", "name": "Jellyfin", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.44", "mac": "BC:24:11:00:23:13", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 9.4, "online": true, "attachTo": "pve" },
  499. { "id": "ct-immich", "name": "Immich", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.45", "mac": "BC:24:11:00:24:14", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 3.3, "online": true, "attachTo": "pve" },
  500. { "id": "ct-gitea", "name": "Gitea", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.46", "mac": "BC:24:11:00:25:15", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 1.2, "online": true, "attachTo": "pve" },
  501. { "id": "ct-uptime-kuma", "name": "Uptime Kuma", "type": "iot", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.47", "mac": "BC:24:11:00:26:16", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.4, "online": true, "attachTo": "pve" },
  502. { "id": "ct-adguard-sync", "name": "AdGuard sync", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.48", "mac": "BC:24:11:00:27:17", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.8, "online": true, "attachTo": "pve" },
  503. { "id": "ct-postgres", "name": "Postgres", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.49", "mac": "BC:24:11:00:28:18", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 2.1, "online": true, "attachTo": "pve" },
  504. { "id": "ct-redis", "name": "Redis", "type": "servidor", "manufacturer": "Proxmox VE (CT)", "ip": "192.168.8.50", "mac": "BC:24:11:00:29:19", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.9, "online": true, "attachTo": "pve" },
  505. { "id": "tv-salon-cable", "name": "TV Salón (cable)", "type": "tv", "manufacturer": "Samsung", "ip": "192.168.8.61", "mac": "8C:EA:48:AA:02:02", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 24.4, "online": true, "attachTo": "dist-flint2-lan3" },
  506. { "id": "impresora-hp", "name": "Impresora HP", "type": "iot", "manufacturer": "HP", "ip": "192.168.8.62", "mac": "3C:D9:2B:AA:03:03", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.1, "online": true, "attachTo": "dist-flint2-lan3" },
  507. { "id": "xbox-one", "name": "Xbox One", "type": "consola", "manufacturer": "Microsoft", "ip": "192.168.8.64", "mac": "7C:ED:8D:AA:05:05", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 4.2, "online": true, "attachTo": "dist-flint2-lan3" },
  508. { "id": "receptor-av", "name": "Receptor AV", "type": "altavoz", "manufacturer": "Denon", "ip": "192.168.8.65", "mac": "00:05:CD:AA:06:06", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.3, "online": true, "attachTo": "dist-flint2-lan3" },
  509. { "id": "deco-orange", "name": "Deco Orange", "type": "tv", "manufacturer": "Sagemcom", "ip": "192.168.8.66", "mac": "48:83:B4:AA:07:07", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 1.1, "online": true, "attachTo": "dist-flint2-lan3" },
  510. { "id": "pc-invitado", "name": "PC invitado", "type": "ordenador", "manufacturer": "-", "ip": "192.168.8.67", "mac": "A2:F4:11:AA:08:08", "routerId": "flint2", "band": "cable", "signalDbm": null, "trafficMbps": 0.8, "online": true, "attachTo": "dist-flint2-lan3" },
  511. ];
  512. const DEMO_ROUTERS = [
  513. { "id": "flint2", "name": "Gateway", "model": "GL.iNet Flint 2 (GL-MT6000)", "modelShort": "GL.iNet Flint 2", "role": "Gateway principal", "roleBadge": "Principal", "ip": "192.168.8.1", "status": "online", "health": 98, "cpu": 23, "ram": 41, "temp": 54, "uptime": "32d 14h", "clients": 26, "backhaul": "cable", "sparkline": [8, 6, 5, 5, 6, 9, 18, 32, 41, 38, 35, 44, 52, 48, 45, 55, 68, 84, 96, 120, 150, 110, 84, 40] },
  514. { "id": "living", "name": "Salón", "model": "OpenWrt AP (Xiaomi AX3000T)", "modelShort": "Xiaomi AX3000T", "role": "Punto de acceso", "roleBadge": "AP", "ip": "192.168.8.2", "status": "online", "health": 95, "cpu": 12, "ram": 38, "temp": 47, "uptime": "32d 14h", "clients": 20, "backhaul": "cable", "sparkline": [4, 3, 3, 2, 3, 5, 10, 22, 28, 26, 24, 30, 38, 35, 33, 42, 55, 72, 88, 105, 132, 92, 61, 28], "lldp": { "chassis": "Flint 2", "mgmt": "192.168.8.1", "caps": "Bridge, Router", "portDesc": "lan1" } },
  515. { "id": "estudio", "name": "Estudio", "model": "OpenWrt (NanoPi R4S)", "modelShort": "NanoPi R4S", "role": "AP + switch", "roleBadge": "AP", "ip": "192.168.8.3", "status": "online", "health": 92, "cpu": 18, "ram": 44, "temp": 51, "uptime": "11d 3h", "clients": 8, "backhaul": "cable", "sparkline": [2, 2, 1, 1, 2, 4, 8, 15, 22, 25, 24, 22, 26, 24, 21, 24, 28, 31, 29, 24, 18, 12, 8, 4], "lldp": { "chassis": "Flint 2", "mgmt": "192.168.8.1", "caps": "Bridge, Router", "portDesc": "lan2" } },
  516. { "id": "patio", "name": "Patio", "model": "OpenWrt (TP-Link EAP225)", "modelShort": "TP-Link EAP225", "role": "AP exterior", "roleBadge": "AP", "ip": "192.168.8.4", "status": "warn", "health": 68, "cpu": 31, "ram": 57, "temp": 71, "uptime": "4d 2h", "clients": 5, "hotMetric": "temp", "backhaul": "wifi", "sparkline": [1, 1, 1, 1, 1, 2, 3, 5, 7, 8, 8, 9, 10, 9, 8, 9, 11, 12, 13, 12, 9, 6, 4, 2] },
  517. ];
  518. /* ===== utilidades de geometria (de model.ts) ===== */
  519. const VB_W = 1000, VB_H = 680;
  520. const GATEWAY_COORD = { x: 500, y: 250, r: 40, label: { x: 446, y: 312, anchor: 'end' } };
  521. const AP_COORDS = [
  522. { x: 195, y: 470, r: 32, label: { x: 124, y: 464, anchor: 'end' } },
  523. { x: 500, y: 505, r: 32, label: { x: 554, y: 500, anchor: 'start' } },
  524. { x: 805, y: 470, r: 32, label: { x: 858, y: 464, anchor: 'start' } },
  525. ];
  526. const INTERNET_COORD = { x: 500, y: 58 };
  527. const PEER_COORDS = [{ x: 265, y: 26 }, { x: 735, y: 26 }, { x: 140, y: 26 }, { x: 860, y: 26 }];
  528. const PEERS_OVERFLOW_COORD = { x: 560, y: 26 };
  529. const UPLINK_PATHS = [
  530. { d: 'M 464 282 C 390 340, 290 400, 224 440', lx: 292, ly: 366 },
  531. { d: 'M 500 292 C 500 360, 500 420, 500 468', lx: 514, ly: 418 },
  532. { d: 'M 536 282 C 610 340, 710 400, 776 440', lx: 664, ly: 366 },
  533. ];
  534. const WG_PATHS = [
  535. { d: 'M 272 44 C 330 82, 410 94, 474 80', dur: 3 },
  536. { d: 'M 728 44 C 670 82, 590 94, 526 80', dur: 3.4 },
  537. ];
  538. const GATEWAY_RINGS = [{ r: 96, cap: 5 }, { r: 130, cap: 8 }];
  539. const AP_RINGS = [{ r: 82, cap: 7 }, { r: 120, cap: 13 }];
  540. const GW_EAST_FAN = [336, 24];
  541. const GW_WEST_FAN = [150, 210];
  542. const AP_WIRED_FAN = [50, 130];
  543. const DIST_FAN_RADIUS = 96;
  544. const DIST_FAN_MAX = 5;
  545. const DIST_RINGS = [{ r: 72, cap: 7 }, { r: 118, cap: 12 }];
  546. const HUB_FAN_RADIUS = 68;
  547. const ROUTER_FAN_RADIUS = 150;
  548. const HYPERVISOR_FAN_RADIUS = 320;
  549. const CT_COLS = 5, CT_DX = 46, CT_DY = 44, CT_OFFSET_Y = 64;
  550. const GW_GRID_MIN = 6, GW_GRID_ROWS = 4, GW_GRID_DX = 56, GW_GRID_DY = 50, GW_GRID_R0 = 160;
  551. const TOPO_COLOR = { accent: '#22D3EE', tunnel: '#A78BFA', ok: '#34D399', warn: '#FBBF24', danger: '#F87171', info: '#60A5FA' };
  552. function bandColor(band, weak) { if (weak)
  553. return TOPO_COLOR.warn; if (band === '5 GHz')
  554. return TOPO_COLOR.accent; if (band === '2.4 GHz')
  555. return TOPO_COLOR.info; return TOPO_COLOR.ok; }
  556. function statusColor(s) { if (s === 'warn')
  557. return TOPO_COLOR.warn; if (s === 'offline')
  558. return TOPO_COLOR.danger; return TOPO_COLOR.ok; }
  559. function linkColor(k, wifi) { if (k === 'wg')
  560. return TOPO_COLOR.tunnel; if (k === 'uplink' && wifi)
  561. return TOPO_COLOR.warn; return TOPO_COLOR.ok; }
  562. function flowFor(mbps, alive = false) { const packets = mbps >= 35 ? 3 : mbps >= 15 ? 2 : mbps >= 2 ? 1 : alive ? 1 : 0; return { packets, packetDur: Math.max(1.6, 5 - mbps / 12) }; }
  563. const rad = (d) => (d * Math.PI) / 180;
  564. const norm = (a) => ((a % 360) + 360) % 360;
  565. function angleTo(x, y, tx, ty) { return norm((Math.atan2(ty - y, tx - x) * 180) / Math.PI); }
  566. function pos(cx, cy, degA, r) { return { x: Math.round((cx + r * Math.cos(rad(degA))) * 10) / 10, y: Math.round((cy + r * Math.sin(rad(degA))) * 10) / 10 }; }
  567. function arcAround(center, half) { const s = norm(center - half); const e = norm(center + half); return s <= e ? [[s, e]] : [[s, 360], [0, e]]; }
  568. function freeArcs(excludes) {
  569. const ex = excludes.map(([s, e]) => [Math.max(0, s), Math.min(360, e)]).filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0]);
  570. const free = [];
  571. let cur = 0;
  572. for (const [s, e] of ex) {
  573. if (s > cur)
  574. free.push([cur, s]);
  575. cur = Math.max(cur, e);
  576. }
  577. if (cur < 360)
  578. free.push([cur, 360]);
  579. return free;
  580. }
  581. function ringLayout(items, node, rings, excludes) {
  582. const free = freeArcs(excludes);
  583. const total = free.reduce((a, [s, e]) => a + (e - s), 0);
  584. if (total <= 0)
  585. return;
  586. let idx = 0;
  587. for (const ring of rings) {
  588. if (idx >= items.length)
  589. break;
  590. const n = Math.min(ring.cap, items.length - idx);
  591. let placed = 0;
  592. for (let ai = 0; ai < free.length && placed < n; ai++) {
  593. const [s, e] = free[ai];
  594. let k = Math.min(Math.round((n * (e - s)) / total), n - placed);
  595. if (ai === free.length - 1)
  596. k = n - placed;
  597. for (let i = 0; i < k; i++) {
  598. const a = s + ((e - s) * (i + 0.5)) / k;
  599. const p = pos(node.x, node.y, a, ring.r);
  600. Object.assign(items[idx++], p);
  601. placed++;
  602. }
  603. }
  604. }
  605. }
  606. function fanLayout(items, node, r, a0, a1) {
  607. if (a1 < a0)
  608. a1 += 360;
  609. const n = items.length;
  610. items.forEach((d, i) => { const a = a0 + ((a1 - a0) * (n === 1 ? 0.5 : i / (n - 1))); Object.assign(d, pos(node.x, node.y, norm(a), r)); });
  611. }
  612. function gridLayoutWest(items, node) {
  613. items.forEach((d, i) => {
  614. const col = Math.floor(i / GW_GRID_ROWS), row = i % GW_GRID_ROWS;
  615. const inThisCol = Math.min(GW_GRID_ROWS, items.length - col * GW_GRID_ROWS);
  616. d.x = node.x - GW_GRID_R0 - col * GW_GRID_DX;
  617. d.y = node.y + (row - (inThisCol - 1) / 2) * GW_GRID_DY;
  618. });
  619. }
  620. function subtreeTraffic(childrenOf, hubId, seen = new Set()) {
  621. if (seen.has(hubId))
  622. return 0;
  623. seen.add(hubId);
  624. let sum = 0;
  625. for (const d of childrenOf(hubId)) {
  626. sum += d.trafficMbps + subtreeTraffic(childrenOf, d.id, seen);
  627. }
  628. return sum;
  629. }
  630. /* ===== builder de modelo (simplificado: sin semantica server-side) ===== */
  631. function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [] }) {
  632. const gateway = routers.find((r) => r.roleBadge === 'Principal') || routers[0];
  633. const aps = routers.filter((r) => r.id !== gateway.id).slice(0, AP_COORDS.length);
  634. const gatewayNode = gateway ? { kind: 'router', id: gateway.id, router: gateway, ...GATEWAY_COORD } : null;
  635. const apNodes = aps.map((router, i) => ({ kind: 'router', id: router.id, router, ...AP_COORDS[i] }));
  636. const routerNodes = gatewayNode ? [gatewayNode, ...apNodes] : apNodes;
  637. const routerById = new Map(routerNodes.map((n) => [n.id, n]));
  638. const internetNode = { id: 'internet', ...INTERNET_COORD };
  639. const managedMacs = new Set(distributionNodes.filter((n) => n.kind === 'managed' && n.mac).map((n) => n.mac.toUpperCase()));
  640. const online = devices.filter((d) => d.online && !managedMacs.has(d.mac.toUpperCase()));
  641. const deviceById = new Map(online.map((d) => [d.id, d]));
  642. const distById = new Map(distributionNodes.map((n) => [n.id, n]));
  643. const hubOf = (d) => {
  644. if (d.attachTo && (routerById.has(d.attachTo) || distById.has(d.attachTo) || deviceById.has(d.attachTo)))
  645. return d.attachTo;
  646. if (isWired(d) && !d.port && gatewayNode)
  647. return gatewayNode.id;
  648. return d.routerId;
  649. };
  650. const isWired = (d) => d.band === 'cable';
  651. const childrenOf = (hubId) => online.filter((d) => hubOf(d) === hubId);
  652. const deviceHubs = new Set();
  653. for (const d of online) {
  654. if (d.attachTo && deviceById.has(d.attachTo))
  655. deviceHubs.add(d.attachTo);
  656. }
  657. const distNodes = [];
  658. const anchorPos = new Map();
  659. const fanArcByRouter = new Map();
  660. const hypervisorHosts = new Set(distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId));
  661. for (const node of routerNodes) {
  662. const isGw = node.id === gatewayNode?.id;
  663. const dists = distributionNodes.filter((n) => n.routerId === node.id && (n.kind === 'inferred' || n.kind === 'managed'));
  664. const directWired = childrenOf(node.id).filter((d) => isWired(d));
  665. const hubs = directWired.filter((d) => deviceHubs.has(d.id));
  666. const plain = directWired.filter((d) => !deviceHubs.has(d.id));
  667. const anchors = [
  668. ...dists.map((n) => ({ id: n.id, kind: 'dist', ref: n })),
  669. ...hubs.map((d) => ({ id: d.id, kind: 'hub', ref: d })),
  670. ...plain.map((d) => ({ id: d.id, kind: 'dev', ref: d })),
  671. ];
  672. if (anchors.length === 0)
  673. continue;
  674. const placed = [];
  675. if (isGw) {
  676. const east = anchors.filter((a) => a.kind === 'dist');
  677. const farWest = anchors.filter((a) => a.kind === 'hub' && hypervisorHosts.has(a.id));
  678. const west = anchors.filter((a) => a.kind !== 'dist' && !farWest.includes(a));
  679. const eastItems = east.map((a) => ({ ...a, x: 0, y: 0 }));
  680. const farWestItems = farWest.map((a) => ({ ...a, x: 0, y: 0 }));
  681. const westItems = west.map((a) => ({ ...a, x: 0, y: 0 }));
  682. fanLayout(eastItems, node, ROUTER_FAN_RADIUS, GW_EAST_FAN[0], GW_EAST_FAN[1]);
  683. fanLayout(farWestItems, node, HYPERVISOR_FAN_RADIUS, 160, 200);
  684. if (westItems.length >= GW_GRID_MIN)
  685. gridLayoutWest(westItems, node);
  686. else
  687. fanLayout(westItems, node, ROUTER_FAN_RADIUS, GW_WEST_FAN[0], GW_WEST_FAN[1]);
  688. placed.push(...eastItems, ...farWestItems, ...westItems);
  689. fanArcByRouter.set(node.id, [...arcAround(0, 26), [GW_WEST_FAN[0] - 8, GW_WEST_FAN[1] + 8]]);
  690. }
  691. else {
  692. const items = anchors.map((a) => ({ ...a, x: 0, y: 0 }));
  693. fanLayout(items, node, ROUTER_FAN_RADIUS, AP_WIRED_FAN[0], AP_WIRED_FAN[1]);
  694. placed.push(...items);
  695. fanArcByRouter.set(node.id, [[AP_WIRED_FAN[0] - 8, AP_WIRED_FAN[1] + 8]]);
  696. }
  697. for (const p of placed) {
  698. anchorPos.set(p.id, { x: p.x, y: p.y });
  699. if (p.kind === 'dist')
  700. distNodes.push({ kind: 'dist', id: p.ref.id, node: p.ref, x: p.x, y: p.y, r: 20 });
  701. }
  702. }
  703. const chips = [];
  704. const mkChip = (d, hubId, isCt = false) => ({
  705. kind: 'chip', id: d.id, device: d, x: 0, y: 0,
  706. size: isWired(d) ? 26 : 24, wired: isWired(d), band: d.band,
  707. weak: d.signalDbm != null && d.signalDbm <= -65, hubId, isCt,
  708. });
  709. const ringRadii = new Map();
  710. for (const node of routerNodes) {
  711. const isGw = node.id === gatewayNode?.id;
  712. const wifi = childrenOf(node.id).filter((d) => !isWired(d)).map((d) => mkChip(d, node.id));
  713. if (wifi.length === 0)
  714. continue;
  715. const excludes = [];
  716. if (isGw) {
  717. excludes.push(...arcAround(270, 14));
  718. if (gatewayNode)
  719. excludes.push(...arcAround(angleTo(gatewayNode.x, gatewayNode.y, gatewayNode.label.x, gatewayNode.label.y), 22));
  720. for (const ap of apNodes)
  721. excludes.push(...arcAround(angleTo(node.x, node.y, ap.x, ap.y), 15));
  722. }
  723. else {
  724. if (gatewayNode)
  725. excludes.push(...arcAround(angleTo(node.x, node.y, gatewayNode.x, gatewayNode.y), 27));
  726. excludes.push(...arcAround(angleTo(node.x, node.y, node.label.x, node.label.y), 22));
  727. }
  728. excludes.push(...(fanArcByRouter.get(node.id) || []));
  729. const baseRings = isGw ? GATEWAY_RINGS : AP_RINGS;
  730. const rings = [...baseRings];
  731. let cap = rings.reduce((a, r) => a + r.cap, 0);
  732. while (cap < wifi.length) {
  733. const last = rings[rings.length - 1];
  734. rings.push({ r: last.r + 30, cap: last.cap + 5 });
  735. cap = rings.reduce((a, r) => a + r.cap, 0);
  736. }
  737. ringRadii.set(node.id, rings.map((r) => r.r));
  738. ringLayout(wifi, node, rings, excludes);
  739. wifi.forEach((c, i) => { if (i >= baseRings[0].cap)
  740. c.size = 22; });
  741. chips.push(...wifi);
  742. }
  743. for (const node of routerNodes) {
  744. for (const d of childrenOf(node.id).filter(isWired)) {
  745. if (deviceHubs.has(d.id))
  746. continue;
  747. const p = anchorPos.get(d.id);
  748. if (!p)
  749. continue;
  750. const c = mkChip(d, node.id);
  751. Object.assign(c, p);
  752. chips.push(c);
  753. }
  754. }
  755. const hubChips = [];
  756. for (const hubId of deviceHubs) {
  757. const hubDev = deviceById.get(hubId);
  758. if (!hubDev)
  759. continue;
  760. const parentHub = hubOf(hubDev);
  761. const p = anchorPos.get(hubId);
  762. if (!p)
  763. continue;
  764. const hc = mkChip(hubDev, parentHub);
  765. Object.assign(hc, p);
  766. hubChips.push(hc);
  767. const kids = hypervisorHosts.has(hubId) ? [] : childrenOf(hubId).map((d) => mkChip(d, hubId));
  768. const center = angleTo((routerById.get(parentHub) || p).x, (routerById.get(parentHub) || p).y, p.x, p.y);
  769. fanLayout(kids, p, HUB_FAN_RADIUS, center - 45, center + 45);
  770. chips.push(...kids);
  771. }
  772. chips.push(...hubChips);
  773. for (const dv of distNodes) {
  774. const kids = childrenOf(dv.id).map((d) => mkChip(d, dv.id));
  775. const rn = routerById.get(dv.node.routerId);
  776. const center = rn ? angleTo(rn.x, rn.y, dv.x, dv.y) : 0;
  777. if (kids.length > DIST_FAN_MAX) {
  778. const excludes = rn ? arcAround(angleTo(dv.x, dv.y, rn.x, rn.y), 20) : [];
  779. const rings = [...DIST_RINGS];
  780. let cap = rings.reduce((a, r) => a + r.cap, 0);
  781. while (cap < kids.length) {
  782. const last = rings[rings.length - 1];
  783. rings.push({ r: last.r + 34, cap: last.cap + 5 });
  784. cap = rings.reduce((a, r) => a + r.cap, 0);
  785. }
  786. ringLayout(kids, dv, rings, excludes);
  787. }
  788. else {
  789. fanLayout(kids, dv, DIST_FAN_RADIUS, center - 68, center + 68);
  790. }
  791. chips.push(...kids);
  792. }
  793. const ctsByHost = new Map(), ctCountByHost = new Map();
  794. for (const dn of distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId)) {
  795. const hostId = dn.hostDeviceId;
  796. const hostChip = chips.find((c) => c.id === hostId);
  797. const kids = childrenOf(hostId).map((d) => mkChip(d, hostId, true));
  798. if (!hostChip || kids.length === 0)
  799. continue;
  800. kids.forEach((c, i) => { c.x = hostChip.x - ((Math.min(kids.length, CT_COLS) - 1) * CT_DX) / 2 + (i % CT_COLS) * CT_DX; c.y = hostChip.y + CT_OFFSET_Y + Math.floor(i / CT_COLS) * CT_DY; c.size = 22; });
  801. ctsByHost.set(hostId, kids);
  802. ctCountByHost.set(hostId, kids.length);
  803. chips.push(...kids);
  804. }
  805. const ringOverflowChips = [];
  806. const activePeers = wireguard.peers.filter((p) => p.active);
  807. const peerNodes = activePeers.slice(0, PEER_COORDS.length).map((peer, i) => ({ kind: 'peer', id: `peer-${peer.id}`, peer, ...PEER_COORDS[i] }));
  808. const hiddenPeers = activePeers.slice(PEER_COORDS.length);
  809. const chipById = new Map(chips.map((c) => [c.id, c]));
  810. const hubPos = (hubId) => {
  811. const rn = routerById.get(hubId);
  812. if (rn)
  813. return { x: rn.x, y: rn.y, r: rn.r };
  814. const dv = distNodes.find((n) => n.id === hubId);
  815. if (dv)
  816. return { x: dv.x, y: dv.y, r: dv.r };
  817. const c = chipById.get(hubId);
  818. if (c)
  819. return { x: c.x, y: c.y, r: c.size / 2 };
  820. return null;
  821. };
  822. const links = [];
  823. if (gatewayNode) {
  824. links.push({
  825. id: 'wan', kind: 'wan',
  826. d: 'M 500 92 C 500 122, 500 162, 500 208',
  827. lx: 518, ly: 162, label: `Fibra ${wan.plan} · ${wan.latencyMs} ms`,
  828. width: 3, ...flowFor(600), from: 'internet', to: gatewayNode.id,
  829. });
  830. }
  831. apNodes.forEach((node, i) => {
  832. const p = UPLINK_PATHS[i];
  833. const isWifi = node.router.backhaul === 'wifi';
  834. const traffic = subtreeTraffic(childrenOf, node.id);
  835. const label = isWifi ? 'WiFi uplink' : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`;
  836. links.push({
  837. id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
  838. d: p.d, lx: p.lx, ly: p.ly, label,
  839. width: isWifi ? 2 : 3, ...flowFor(Math.max(traffic, isWifi ? 40 : 120)),
  840. from: gatewayNode?.id || 'internet', to: node.id,
  841. });
  842. });
  843. for (const dv of distNodes) {
  844. const rn = routerById.get(dv.node.routerId);
  845. if (!rn)
  846. continue;
  847. const edge = pos(rn.x, rn.y, angleTo(rn.x, rn.y, dv.x, dv.y), rn.r + 2);
  848. const mid = { x: (edge.x + dv.x) / 2, y: (edge.y + dv.y) / 2 };
  849. links.push({
  850. id: `dist-${dv.id}`, kind: 'dist',
  851. d: `M ${edge.x} ${edge.y} Q ${mid.x + 6} ${mid.y - 6}, ${dv.x} ${dv.y}`,
  852. lx: 0, ly: 0, label: '',
  853. width: 2.5, ...flowFor(subtreeTraffic(childrenOf, dv.id), true),
  854. from: dv.node.routerId, to: dv.id,
  855. });
  856. }
  857. for (const chip of chips) {
  858. if (chip.isCt || !chip.wired)
  859. continue;
  860. const hub = hubPos(chip.hubId);
  861. if (!hub)
  862. continue;
  863. const a = angleTo(hub.x, hub.y, chip.x, chip.y);
  864. const edge = pos(hub.x, hub.y, a, hub.r + 2);
  865. const dx = chip.x - edge.x, dy = chip.y - edge.y;
  866. const c1x = edge.x + dx * 0.5 - dy * 0.1;
  867. const c1y = edge.y + dy * 0.5 + dx * 0.1;
  868. const mbps = deviceHubs.has(chip.id) ? chip.device.trafficMbps + subtreeTraffic(childrenOf, chip.id) : chip.device.trafficMbps;
  869. links.push({
  870. id: `wired-${chip.id}`, kind: 'wired',
  871. d: `M ${edge.x} ${edge.y} Q ${c1x} ${c1y}, ${chip.x} ${chip.y}`,
  872. lx: 0, ly: 0, label: '',
  873. width: 1.4, ...flowFor(mbps, true),
  874. from: chip.hubId, to: chip.id,
  875. });
  876. }
  877. for (const [hostId, cts] of ctsByHost) {
  878. const hostChip = chipById.get(hostId);
  879. if (!hostChip)
  880. continue;
  881. for (const ct of cts) {
  882. links.push({
  883. id: `wired-${ct.id}`, kind: 'wired',
  884. d: `M ${hostChip.x} ${hostChip.y + hostChip.size / 2} L ${ct.x} ${ct.y - ct.size / 2}`,
  885. lx: 0, ly: 0, label: '',
  886. width: 1.2, ...flowFor(ct.device.trafficMbps, true),
  887. from: hostId, to: ct.id,
  888. });
  889. }
  890. }
  891. peerNodes.forEach((node, i) => {
  892. const p = WG_PATHS[i] || { d: '', dur: 3.2 };
  893. const d = p.d || `M ${node.x + 7} ${node.y + 18} C ${node.x + 60} ${node.y + 56}, ${internetNode.x - 40} ${internetNode.y + 36}, ${internetNode.x - 26} ${internetNode.y + 22}`;
  894. links.push({
  895. id: `wg-${node.peer.id}`, kind: 'wg',
  896. d, lx: 0, ly: 0, label: '',
  897. width: 2, packets: 1, packetDur: p.dur,
  898. from: node.id, to: 'internet',
  899. });
  900. });
  901. return {
  902. gatewayNode, apNodes, routerNodes, internetNode, peerNodes, hiddenPeers,
  903. chips, distNodes, ctsByHost, ctCountByHost, ringRadii, ringOverflowChips, links,
  904. wan,
  905. };
  906. }
  907. /* ===== iconos SVG inline ===== */
  908. function drawIcon(type, size, parent) {
  909. const s = size || 14;
  910. const half = s / 2;
  911. const scale = s / 24;
  912. const mkp = (d) => {
  913. const el = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  914. el.setAttribute('d', d);
  915. el.setAttribute('transform', `translate(${-half},${-half}) scale(${scale})`);
  916. el.setAttribute('fill', 'none');
  917. el.setAttribute('stroke', 'currentColor');
  918. el.setAttribute('stroke-width', '1.75');
  919. el.setAttribute('stroke-linecap', 'round');
  920. el.setAttribute('stroke-linejoin', 'round');
  921. parent.appendChild(el);
  922. return el;
  923. };
  924. const map = {
  925. ordenador: 'M3 4h18v12H3z M8 16v4 M16 16v4 M6 20h12',
  926. portatil: 'M4 5h16v10H4z M2 17h20v2H2z',
  927. movil: 'M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z',
  928. tablet: 'M5 2h14a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z',
  929. tv: 'M2 7h20v12H2z M8 3l4 4 4-4',
  930. consola: 'M6 11h2v2H6zm10 0h2v2h-2zm-6 2h4v-4h-4z M4 7h16a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2z',
  931. iot: 'M12 2a6 6 0 0 0-6 6c0 2.22 1.21 4.16 3 5.2V19a3 3 0 0 0 6 0v-5.8a6 6 0 0 0 0-10.4z',
  932. camara: 'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z M12 17a4 4 0 1 0 0-8 4 4 0 0 0 0 8z',
  933. altavoz: 'M18 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z M12 18a4 4 0 0 0 0-8',
  934. servidor: 'M6 2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z M6 7h12 M6 12h12 M6 17h12',
  935. switch: 'M4 10h16v8H4z M8 10V6 M16 10V6',
  936. desconocido: 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z M9 9a3 3 0 1 1 6 0c0 2-3 3-3 5',
  937. };
  938. mkp(map[type] || map.desconocido);
  939. }
  940. /* ===== render SVG fiel ===== */
  941. function drawTopology() {
  942. const model = buildTopologyModel({
  943. routers: DEMO_ROUTERS, devices: DEMO_DEVICES, wan: DEMO_WAN,
  944. wireguard: DEMO_WG, distributionNodes: DEMO_DISTRIBUTION,
  945. });
  946. const svg = document.getElementById('topoSvg');
  947. svg.innerHTML = '';
  948. const ns = 'http://www.w3.org/2000/svg';
  949. const mk = (tag, attrs = {}, parent = svg) => {
  950. const el = document.createElementNS(ns, tag);
  951. for (const [k, v] of Object.entries(attrs))
  952. if (v !== undefined && v !== null)
  953. el.setAttribute(k, v);
  954. if (parent)
  955. parent.appendChild(el);
  956. return el;
  957. };
  958. // Lección de la app (bug chips invisibles): nunca atributo transform y
  959. // animación CSS de scale en el mismo <g> - el transform CSS machaca el
  960. // translate del atributo y los nodos colapsan en (0,0). El translate va en
  961. // el <g> padre y la animación (opacity/scale con transform-box) en un hijo.
  962. const nodeGroup = (x, y) => {
  963. const outer = mk('g', { transform: `translate(${x} ${y})` });
  964. return mk('g', { class: 'topo-node on' }, outer);
  965. };
  966. // defs
  967. const defs = mk('defs');
  968. const grad = mk('linearGradient', { id: 'topo-gw-grad', x1: 0, y1: 0, x2: 1, y2: 1 }, defs);
  969. mk('stop', { offset: '0%', 'stop-color': TOPO_COLOR.accent, 'stop-opacity': 0.28 }, grad);
  970. mk('stop', { offset: '100%', 'stop-color': TOPO_COLOR.tunnel, 'stop-opacity': 0.28 }, grad);
  971. // anillos guia wifi
  972. const guidesG = mk('g', { 'class': 'topo-guides', 'aria-hidden': 'true' });
  973. for (const node of model.routerNodes) {
  974. const radii = model.ringRadii.get(node.id) || (node.id === model.gatewayNode?.id ? [96, 130] : [82, 120]);
  975. for (const r of radii)
  976. mk('circle', { cx: node.x, cy: node.y, r, class: 'topo-guide' }, guidesG);
  977. }
  978. // enlaces
  979. const linksG = mk('g');
  980. for (const link of model.links) {
  981. const isWg = link.kind === 'wg';
  982. const isWifiUp = link.kind === 'uplink' && link.wifi;
  983. const stroke = linkColor(link.kind, link.wifi);
  984. const baseOpacity = link.kind === 'wired' ? 0.45 : link.kind === 'dist' ? 0.55 : isWifiUp ? 0.8 : link.kind === 'uplink' ? 0.55 : 0.9;
  985. const path = mk('path', { d: link.d, fill: 'none', stroke, 'stroke-width': link.width, 'stroke-linecap': 'round',
  986. 'stroke-dasharray': isWg ? '7 7' : isWifiUp ? '8 6' : undefined, opacity: baseOpacity,
  987. id: `topo-link-${link.id}`, class: 'topo-edge on' }, linksG);
  988. if (isWg) {
  989. mk('path', { d: link.d, fill: 'none', stroke: TOPO_COLOR.tunnel, 'stroke-width': link.width, 'stroke-linecap': 'round',
  990. 'stroke-dasharray': '7 7', opacity: 0.9, class: 'topo-wg-flow' }, linksG);
  991. }
  992. // paquetes animados via CSS offset-path
  993. if (link.packets > 0) {
  994. for (let i = 0; i < link.packets; i++) {
  995. const begin = -((link.packetDur / link.packets) * i);
  996. mk('circle', {
  997. r: 2.6, fill: stroke, opacity: 0.95, class: 'topo-packet',
  998. style: `offset-path: path('${link.d.replace(/'/g, "\\'")}'); animation: packetMove ${link.packetDur}s linear infinite; animation-delay: ${begin}s`,
  999. }, linksG);
  1000. }
  1001. }
  1002. }
  1003. // internet
  1004. const inetG = nodeGroup(model.internetNode.x, model.internetNode.y);
  1005. mk('circle', { r: 42, fill: TOPO_COLOR.ok, opacity: 0.08 }, inetG);
  1006. const orbit = mk('g', { 'aria-hidden': 'true', class: 'topo-orbit' }, inetG);
  1007. mk('circle', { r: 38, fill: 'none', stroke: TOPO_COLOR.ok, 'stroke-width': 1.2, 'stroke-dasharray': '3 7', opacity: 0.55 }, orbit);
  1008. mk('circle', { r: 3, fill: TOPO_COLOR.ok, cx: 0, cy: -38 }, orbit);
  1009. mk('circle', { r: 28, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.ok, 'stroke-width': 2 }, inetG);
  1010. mk('path', { d: 'M19.3 11.7a5.6 5.6 0 0 0-8.2-3.5A4.5 4.5 0 0 0 4.5 12.5 4.5 4.5 0 0 0 9 17h11a3.5 3.5 0 0 0 0-7h-1.2l-1.5-1.3z',
  1011. fill: 'none', stroke: TOPO_COLOR.ok, 'stroke-width': 1.75, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, inetG);
  1012. // routers
  1013. model.routerNodes.forEach((node, i) => {
  1014. const isGw = node.router.roleBadge === 'Principal';
  1015. const isWarn = node.router.status === 'warn';
  1016. const g = nodeGroup(node.x, node.y);
  1017. if (isGw)
  1018. mk('circle', { r: node.r + 18, fill: TOPO_COLOR.accent, opacity: 0.1, class: 'topo-halo' }, g);
  1019. if (isWarn) {
  1020. mk('circle', { r: node.r + 8, fill: 'none', stroke: TOPO_COLOR.warn, 'stroke-width': 2, class: 'topo-warn-pulse' }, g);
  1021. }
  1022. mk('circle', { r: node.r, fill: isGw ? 'url(#topo-gw-grad)' : 'rgb(var(--elevated))',
  1023. stroke: isWarn ? TOPO_COLOR.warn : isGw ? TOPO_COLOR.accent : 'rgb(var(--border-strong))', 'stroke-width': isGw || isWarn ? 2 : 1.5 }, g);
  1024. // status ring
  1025. const R = node.r + 6, C = 2 * Math.PI * R;
  1026. const target = C * (1 - node.router.health / 100);
  1027. const ring = mk('circle', { r: R, fill: 'none', stroke: statusColor(node.router.status), 'stroke-width': 3,
  1028. 'stroke-dasharray': C, 'stroke-dashoffset': target, 'stroke-linecap': 'round', transform: 'rotate(-90)' }, g);
  1029. // router icon
  1030. mk('path', { d: 'M4 10h16v8H4z M8 10V6 M16 10V6 M12 2v4', fill: 'none', stroke: isWarn ? TOPO_COLOR.warn : TOPO_COLOR.accent,
  1031. 'stroke-width': 1.75, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, g);
  1032. });
  1033. // peers
  1034. model.peerNodes.forEach((node, i) => {
  1035. const isMovil = node.peer.type === 'movil';
  1036. const g = nodeGroup(node.x, node.y);
  1037. const pulse = mk('circle', { r: 22, fill: 'none', stroke: TOPO_COLOR.tunnel, 'stroke-width': 1.5, class: 'topo-peer-pulse' }, g);
  1038. mk('rect', { x: -18, y: -18, width: 36, height: 36, rx: 11, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.tunnel, 'stroke-width': 1.5 }, g);
  1039. const path = isMovil
  1040. ? 'M7 2h10a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z'
  1041. : 'M4 5h16v10H4z M2 17h20v2H2z';
  1042. mk('path', { d: path, fill: 'none', stroke: TOPO_COLOR.tunnel, 'stroke-width': 1.75, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, g);
  1043. });
  1044. // hidden peers +N
  1045. if (model.hiddenPeers.length > 0) {
  1046. const g = nodeGroup(PEERS_OVERFLOW_COORD.x, PEERS_OVERFLOW_COORD.y);
  1047. mk('rect', { x: -15, y: -11, width: 30, height: 22, rx: 8, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.tunnel, 'stroke-width': 1.5 }, g);
  1048. mk('text', { x: 0, y: 3.5, 'text-anchor': 'middle', 'font-size': 9.5, 'font-weight': 700, fill: TOPO_COLOR.tunnel }, g).textContent = '+' + model.hiddenPeers.length;
  1049. }
  1050. // distnodes
  1051. model.distNodes.forEach((dv) => {
  1052. const managed = dv.node.kind === 'managed';
  1053. const g = nodeGroup(dv.x, dv.y);
  1054. mk('circle', { r: dv.r + 5, fill: 'none', stroke: managed ? TOPO_COLOR.accent : 'rgb(var(--text-muted))', 'stroke-width': 1,
  1055. 'stroke-dasharray': managed ? undefined : '2 5', opacity: managed ? 0.5 : 0.6 }, g);
  1056. mk('circle', { r: dv.r, fill: managed ? 'rgb(var(--elevated))' : 'rgb(var(--elevated) / 0.65)',
  1057. stroke: managed ? TOPO_COLOR.accent : 'rgb(var(--text-muted))', 'stroke-width': 1.5, 'stroke-dasharray': managed ? undefined : '4 4' }, g);
  1058. mk('path', { d: 'M4 10h16v8H4z M8 10V6 M16 10V6', fill: 'none', stroke: managed ? TOPO_COLOR.accent : 'rgb(var(--text-secondary))', 'stroke-width': 1.75 }, g);
  1059. if (managed) {
  1060. mk('rect', { x: dv.r - 4, y: -dv.r - 4, width: 22, height: 10, rx: 5, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.accent, 'stroke-width': 1 }, g);
  1061. mk('text', { x: dv.r + 7, y: -dv.r + 3.4, 'text-anchor': 'middle', 'font-size': 6.5, 'font-weight': 800, fill: TOPO_COLOR.accent, 'letter-spacing': '0.04em' }, g).textContent = 'LLDP';
  1062. }
  1063. });
  1064. // chips
  1065. model.chips.forEach((chip) => {
  1066. const d = chip.device, S = chip.size, half = S / 2;
  1067. const stroke = d.lldp ? TOPO_COLOR.accent : chip.wired ? TOPO_COLOR.ok : 'rgb(var(--border-strong))';
  1068. const g = nodeGroup(chip.x, chip.y);
  1069. const rect = mk('rect', { x: -half, y: -half, width: S, height: S, rx: 7, fill: 'rgb(var(--elevated))', stroke, 'stroke-width': chip.wired ? 1.3 : 1.1 }, g);
  1070. const iconG = mk('g', { style: `color: ${chip.wired ? TOPO_COLOR.ok : 'rgb(var(--text-primary))'}` }, g);
  1071. drawIcon(d.type, 14, iconG);
  1072. if (!chip.wired) {
  1073. mk('circle', { cx: half - 2, cy: half - 2, r: 3.8, fill: bandColor(chip.band, chip.weak), stroke: 'rgb(var(--canvas))', 'stroke-width': 1.4 }, g);
  1074. }
  1075. if (d.lldp) {
  1076. mk('rect', { x: half - 4, y: -half - 4, width: 22, height: 10, rx: 5, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.accent, 'stroke-width': 1 }, g);
  1077. mk('text', { x: half + 7, y: -half + 3.4, 'text-anchor': 'middle', 'font-size': 6.5, 'font-weight': 800, fill: TOPO_COLOR.accent, 'letter-spacing': '0.04em' }, g).textContent = 'LLDP';
  1078. }
  1079. const ctCount = model.ctCountByHost.get(chip.id) || 0;
  1080. if (ctCount > 0) {
  1081. mk('circle', { cx: half + 1, cy: -half - 1, r: 8, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.ok, 'stroke-width': 1.2 }, g);
  1082. mk('text', { x: half + 1, y: -half + 2, 'text-anchor': 'middle', 'font-size': 8, 'font-weight': 700, fill: TOPO_COLOR.ok }, g).textContent = '+' + ctCount;
  1083. }
  1084. mk('title', {}, g).textContent = tName(d.name);
  1085. });
  1086. // etiquetas
  1087. const labelsG = mk('g', { class: 'topo-labels', 'pointer-events': 'none', 'aria-hidden': 'true' });
  1088. function label(x, y, anchor, title, sub, subColor) {
  1089. const g = mk('g', {}, labelsG);
  1090. mk('text', { x, y, 'text-anchor': anchor, 'font-size': 13, 'font-weight': 600, fill: 'rgb(var(--text-primary))', stroke: 'rgb(var(--canvas))', 'stroke-width': 4, style: 'paint-order: stroke' }, g).textContent = title;
  1091. mk('text', { x, y: y + 15, 'text-anchor': anchor, 'font-size': 10.5, fill: subColor || 'rgb(var(--text-secondary))', stroke: 'rgb(var(--canvas))', 'stroke-width': 3, style: 'paint-order: stroke' }, g).textContent = sub;
  1092. }
  1093. const linkLabelText = (l) => {
  1094. if (l.kind === 'wan')
  1095. return t('topo.fiber').replace('{plan}', model.wan.plan).replace('{latency}', model.wan.latencyMs);
  1096. if (l.kind === 'uplink')
  1097. return l.wifi ? t('topo.wifiUplink') : t('topo.cable1g') + (l.label.includes('LLDP') ? ' · LLDP' : '');
  1098. return '';
  1099. };
  1100. label(548, 54, 'start', `${t('topo.inet')} · ${model.wan.isp}`, `${model.wan.plan} · ${model.wan.latencyMs} ms`);
  1101. if (model.gatewayNode) {
  1102. const n = model.gatewayNode;
  1103. label(n.label.x, n.label.y, n.label.anchor, tName(n.router.name), `${n.router.modelShort} · ${n.router.roleBadge} · ${n.router.clients} ${t('topo.clients')}`);
  1104. }
  1105. model.apNodes.forEach((n) => {
  1106. const warn = n.router.status === 'warn';
  1107. label(n.label.x, n.label.y, n.label.anchor, tName(n.router.name), warn ? `${n.router.clients} ${t('topo.clients')} · ${t('routers.warn')}` : `${n.router.clients} ${t('topo.clients')}`, warn ? TOPO_COLOR.warn : undefined);
  1108. });
  1109. model.distNodes.forEach((dv) => {
  1110. if (dv.node.kind === 'managed')
  1111. label(dv.x, dv.y - 34, 'middle', dv.node.name ? tName(dv.node.name) : t('topo.managed'), `${dv.node.ip || 'LLDP'} · ${dv.node.port}`, TOPO_COLOR.accent);
  1112. else
  1113. label(dv.x, dv.y - 34, 'middle', t('topo.inferredSwitch'), `${dv.node.port}`);
  1114. });
  1115. for (const [hostId] of model.ctsByHost) {
  1116. const host = model.chips.find((c) => c.id === hostId);
  1117. if (!host)
  1118. continue;
  1119. label(host.x, host.y - 38, 'middle', tName(host.device.name), `${t('topo.hypervisor')} · ${model.ctCountByHost.get(hostId) || 0} CT`);
  1120. }
  1121. model.peerNodes.forEach((n, i) => label(n.x + (i % 2 ? -26 : 26), n.y - 4, i % 2 ? 'end' : 'start', tName(n.peer.name), t('topo.viaInternet'), TOPO_COLOR.tunnel));
  1122. model.links.filter((l) => l.label).forEach((l) => {
  1123. mk('text', { x: l.lx, y: l.ly, 'font-size': 10, fill: 'rgb(var(--text-muted))', stroke: 'rgb(var(--canvas))', 'stroke-width': 3, style: 'paint-order: stroke', class: 'font-mono' }, labelsG).textContent = linkLabelText(l);
  1124. });
  1125. }
  1126. function buildTopo() {
  1127. if (topoBuilt)
  1128. return;
  1129. topoBuilt = true;
  1130. drawTopology();
  1131. }
  1132. function renderTopoNames() {
  1133. if (topoBuilt)
  1134. drawTopology();
  1135. }
  1136. function buildRouters() {
  1137. const grid = document.getElementById('routerGrid');
  1138. const C = 2 * Math.PI * 25; // r=25 para que el anillo (stroke 5) quepa en el viewBox 56x56 y no se recorte
  1139. grid.innerHTML = DEMO_ROUTERS.map(r => {
  1140. const isWarn = r.status === 'warn';
  1141. const statusColor = isWarn ? 'rgb(var(--warn))' : 'rgb(var(--ok))';
  1142. const healthDash = C * (1 - r.health / 100);
  1143. const sparkPath = r.sparkline.map((v, i) => `${i === 0 ? 'M' : 'L'}${(i / (r.sparkline.length - 1)) * 100} ${28 - (v / 70) * 28}`).join(' ');
  1144. return `
  1145. <div class="rcard card ${isWarn ? 'warn' : ''}">
  1146. <div class="rt">
  1147. <div class="nameblock">
  1148. <div class="iconbox">
  1149. <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14h16v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-5z"/><path d="M8 6h8"/><path d="M6 9h12"/><path d="M10 3h4"/></svg>
  1150. </div>
  1151. <div>
  1152. <span class="name">${tName(r.name)}</span>
  1153. <span class="model">${r.model}</span>
  1154. <span class="rolepill">${t(r.roleBadge === 'Principal' ? 'routers.roleGW' : 'routers.roleAP')}</span>
  1155. </div>
  1156. </div>
  1157. <div class="ring-wrap" style="width:56px;height:56px;">
  1158. <svg width="56" height="56" viewBox="0 0 56 56" style="transform:rotate(-90deg);">
  1159. <circle cx="28" cy="28" r="25" fill="none" stroke="rgb(var(--border))" stroke-width="5"/>
  1160. <circle class="router-health-ring" cx="28" cy="28" r="25" fill="none" stroke="${statusColor}" stroke-width="5" stroke-linecap="round"
  1161. stroke-dasharray="${C}" stroke-dashoffset="${C}" data-target="${healthDash}"/>
  1162. </svg>
  1163. <div class="ring-center" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;">
  1164. <span class="font-mono" style="font-size:0.78rem;font-weight:700;">${r.health}</span>
  1165. </div>
  1166. </div>
  1167. </div>
  1168. <div class="minimetrics">
  1169. <div class="${r.cpu > 40 ? 'hot' : ''}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M9 9h6v6H9z"/><path d="M9 1v3"/><path d="M15 1v3"/><path d="M9 20v3"/><path d="M15 20v3"/><path d="M20 9h3"/><path d="M20 15h3"/><path d="M1 9h3"/><path d="M1 15h3"/></svg> CPU <span class="font-mono">${r.cpu}%</span></div>
  1170. <div class="${r.ram > 60 ? 'hot' : ''}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/><path d="M9 7h6"/><path d="M9 11h6"/></svg> RAM <span class="font-mono">${r.ram}%</span></div>
  1171. <div class="${r.temp > 70 ? 'hot' : ''}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0"/></svg> ${t('routers.temp')} <span class="font-mono">${r.temp}°C</span></div>
  1172. <div><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg> ${t('routers.clients')} <span class="font-mono">${r.clients}</span></div>
  1173. </div>
  1174. <div class="bottom">
  1175. <svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><path d="${sparkPath}" vector-effect="non-scaling-stroke"/></svg>
  1176. <span class="font-mono" style="font-size:0.75rem;color:rgb(var(--text-muted));">${r.uptime}</span>
  1177. <span class="statuspill ${r.status}"><span class="dot"></span>${t(r.status === 'ok' ? 'routers.online' : 'routers.warn')}</span>
  1178. <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:1rem;height:1rem;color:rgb(var(--text-muted));"><path d="m9 18 6-6-6-6"/></svg>
  1179. </div>
  1180. </div>
  1181. `;
  1182. }).join('');
  1183. routersBuilt = true;
  1184. }
  1185. function fillRouterBars(instant) {
  1186. const grid = document.getElementById('routerGrid');
  1187. grid.querySelectorAll('.router-health-ring').forEach(ring => {
  1188. const target = ring.dataset.target;
  1189. if (instant || reduceMotion)
  1190. ring.style.strokeDashoffset = target;
  1191. else
  1192. setTimeout(() => ring.style.strokeDashoffset = target, 80);
  1193. });
  1194. }
  1195. function renderRouterNames() {
  1196. if (!routersBuilt)
  1197. return;
  1198. buildRouters();
  1199. if (routersPlayed)
  1200. fillRouterBars(true);
  1201. }
  1202. function playRouters() {
  1203. buildRouters();
  1204. routersBuilt = true;
  1205. if (routersPlayed) {
  1206. fillRouterBars(true);
  1207. return;
  1208. }
  1209. routersPlayed = true;
  1210. fillRouterBars(false);
  1211. }
  1212. /* ---------- stage 4: adguard (como la tarjeta de la app) ---------- */
  1213. let agPlayed = false;
  1214. const AG_DONUT_C = 248.2;
  1215. function renderAdGuardTexts() {
  1216. const ag = DEMO_ADGUARD;
  1217. const set = (id, v) => { const el = document.getElementById(id); if (el)
  1218. el.textContent = v; };
  1219. set('agBlockedPct', fmtLocale(ag.blockedPct, 1) + '%');
  1220. set('agBlockedOf', t('adguard.blockedOf', { blocked: fmtLocale(ag.blocked24h), total: fmtLocale(ag.queries24h) }));
  1221. set('agTrackers', fmtLocale(ag.trackersBlocked));
  1222. set('agDns', fmtLocale(ag.dnsLatencyMs) + ' ms');
  1223. }
  1224. function playAdGuard() {
  1225. renderAdGuardTexts();
  1226. const ag = DEMO_ADGUARD;
  1227. const arc = document.getElementById('agDonutArc');
  1228. if (agPlayed)
  1229. return;
  1230. agPlayed = true;
  1231. // animación del arco del donut
  1232. if (reduceMotion) {
  1233. arc.style.strokeDashoffset = String(AG_DONUT_C * (1 - ag.blockedPct / 100));
  1234. }
  1235. else {
  1236. const start = performance.now(), dur = 1100;
  1237. function frame(now) {
  1238. const p = Math.min(1, (now - start) / dur);
  1239. const e = easeOutCubic(p);
  1240. arc.style.strokeDashoffset = String(AG_DONUT_C * (1 - (ag.blockedPct / 100) * e));
  1241. if (p < 1)
  1242. requestAnimationFrame(frame);
  1243. }
  1244. requestAnimationFrame(frame);
  1245. }
  1246. // barras de dominios bloqueados
  1247. const bars = document.getElementById('agBars');
  1248. if (!bars.childElementCount) {
  1249. const max = ag.topBlocked[0].count;
  1250. bars.innerHTML = ag.topBlocked.map((x) => `
  1251. <div class="ag-bar-row">
  1252. <span class="d">${x.domain}</span>
  1253. <div class="bar"><i data-w="${Math.round((x.count / max) * 100)}"></i></div>
  1254. <span class="n">${fmtLocale(x.count)}</span>
  1255. </div>
  1256. `).join('');
  1257. }
  1258. bars.querySelectorAll('.bar i').forEach((bar, i) => {
  1259. const w = bar.dataset.w;
  1260. if (reduceMotion) {
  1261. bar.style.width = w + '%';
  1262. return;
  1263. }
  1264. setTimeout(() => { bar.style.width = w + '%'; }, 200 + i * 120);
  1265. });
  1266. }
  1267. /* ---------- stage 6: agente OpenWrt (terminal) ---------- */
  1268. let agentPlayed = false;
  1269. function playAgent() {
  1270. if (agentPlayed)
  1271. return;
  1272. agentPlayed = true;
  1273. const lines = document.querySelectorAll('#stage6 .term-line');
  1274. if (!lines.length)
  1275. return;
  1276. if (reduceMotion) {
  1277. lines.forEach(l => l.style.opacity = '1');
  1278. return;
  1279. }
  1280. lines.forEach((l, i) => {
  1281. l.style.opacity = '0';
  1282. setTimeout(() => { l.style.opacity = '1'; l.style.transition = 'opacity 180ms ease'; }, 200 + i * 160);
  1283. });
  1284. }
  1285. const ALERT_ICONS = {
  1286. warn: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  1287. ok: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',
  1288. info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  1289. accent: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',
  1290. };
  1291. function renderAlerts() {
  1292. const feed = document.getElementById('alertFeed');
  1293. if (!feed)
  1294. return;
  1295. const items = [
  1296. { tone: 'warn', text: t('alerts.a1'), sub: `2 min ${t('alerts.ago')}` },
  1297. { tone: 'accent', text: t('alerts.a2'), sub: `11 min ${t('alerts.ago')}` },
  1298. { tone: 'info', text: t('alerts.a3'), sub: `1 h ${t('alerts.ago')}` },
  1299. { tone: 'ok', text: t('alerts.a4'), sub: `2 h ${t('alerts.ago')}` },
  1300. ];
  1301. feed.innerHTML = items.map(a => `
  1302. <div class="alert-item ${a.tone}">
  1303. <span class="ico">${ALERT_ICONS[a.tone]}</span>
  1304. <span><span class="t">${a.text}</span><span class="s" style="display:block;">${a.sub}</span></span>
  1305. </div>
  1306. `).join('');
  1307. if (alertsPlayed)
  1308. feed.querySelectorAll('.alert-item').forEach(el => el.classList.add('on'));
  1309. }
  1310. let alertsPlayed = false;
  1311. function playAlerts() {
  1312. renderAlerts();
  1313. if (alertsPlayed)
  1314. return;
  1315. alertsPlayed = true;
  1316. document.querySelectorAll('#alertFeed .alert-item').forEach((el, i) => {
  1317. if (reduceMotion) {
  1318. el.classList.add('on');
  1319. return;
  1320. }
  1321. setTimeout(() => el.classList.add('on'), 150 + i * 260);
  1322. });
  1323. }
  1324. /* ---------- teatro: control de stages por scroll ---------- */
  1325. const STAGE_PLAYERS = [playRing, playTraffic, buildTopo, playRouters, playAdGuard, playAlerts, playAgent];
  1326. let currentStage = -1;
  1327. function setStage(i) {
  1328. if (i === currentStage)
  1329. return;
  1330. currentStage = i;
  1331. document.querySelectorAll('.stage').forEach((s, idx) => s.classList.toggle('active', idx === i));
  1332. document.querySelectorAll('.tstep').forEach(s => {
  1333. s.style.opacity = parseInt(s.dataset.stage, 10) === i ? '1' : '';
  1334. });
  1335. STAGE_PLAYERS[i]();
  1336. }
  1337. function initTheater() {
  1338. const steps = [...document.querySelectorAll('.tstep')];
  1339. if (!steps.length)
  1340. return;
  1341. if (!('IntersectionObserver' in window)) {
  1342. setStage(0);
  1343. return;
  1344. }
  1345. const io = new IntersectionObserver(entries => {
  1346. entries.forEach(en => { if (en.isIntersecting)
  1347. setStage(parseInt(en.target.dataset.stage, 10)); });
  1348. }, { rootMargin: '-42% 0px -42% 0px', threshold: 0 });
  1349. steps.forEach(s => io.observe(s));
  1350. setStage(0);
  1351. }
  1352. /* ---------- reveals on scroll ---------- */
  1353. function initReveals() {
  1354. const els = document.querySelectorAll('.reveal');
  1355. if (reduceMotion || !('IntersectionObserver' in window)) {
  1356. els.forEach(e => e.classList.add('in'));
  1357. return;
  1358. }
  1359. const io = new IntersectionObserver(entries => {
  1360. entries.forEach(en => { if (en.isIntersecting) {
  1361. en.target.classList.add('in');
  1362. io.unobserve(en.target);
  1363. } });
  1364. }, { threshold: 0.12 });
  1365. els.forEach(e => io.observe(e));
  1366. }
  1367. /* ---------- widget apariencia ---------- */
  1368. const MODE_KEY = 'netpulse-web-theme-mode';
  1369. let themeMode = 'dark';
  1370. function readStore(k) { try {
  1371. return localStorage.getItem(k);
  1372. }
  1373. catch {
  1374. return null;
  1375. } }
  1376. function writeStore(k, v) { try {
  1377. localStorage.setItem(k, v);
  1378. }
  1379. catch { /* privado */ } }
  1380. function applyTheme() {
  1381. const root = document.documentElement;
  1382. let light = false;
  1383. if (themeMode === 'light')
  1384. light = true;
  1385. else if (themeMode === 'system')
  1386. light = window.matchMedia('(prefers-color-scheme: light)').matches;
  1387. root.classList.toggle('light', light);
  1388. const meta = document.querySelector('meta[name="theme-color"]');
  1389. if (meta)
  1390. meta.content = light ? '#F3F5F9' : '#070B12';
  1391. if (typeof renderShot === 'function')
  1392. renderShot();
  1393. if (typeof renderHashots === 'function')
  1394. renderHashots();
  1395. }
  1396. function updateAppearancePanel() {
  1397. document.querySelectorAll('#themeSeg button').forEach(b => b.classList.toggle('on', b.dataset.mode === themeMode));
  1398. }
  1399. function setMode(m) {
  1400. themeMode = m;
  1401. writeStore(MODE_KEY, m);
  1402. applyTheme();
  1403. updateAppearancePanel();
  1404. }
  1405. window.setMode = setMode;
  1406. function initAppearance() {
  1407. themeMode = readStore(MODE_KEY) || 'dark';
  1408. applyTheme();
  1409. updateAppearancePanel();
  1410. const fab = document.getElementById('appFab');
  1411. const panel = document.getElementById('appPanel');
  1412. fab.addEventListener('click', () => { panel.classList.toggle('open'); fab.setAttribute('aria-expanded', String(panel.classList.contains('open'))); });
  1413. document.addEventListener('click', e => { if (!panel.contains(e.target) && !fab.contains(e.target))
  1414. panel.classList.remove('open'); });
  1415. document.addEventListener('keydown', e => { if (e.key === 'Escape')
  1416. panel.classList.remove('open'); });
  1417. document.querySelectorAll('#themeSeg button').forEach(b => b.addEventListener('click', () => setMode(b.dataset.mode)));
  1418. window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => { if (themeMode === 'system')
  1419. applyTheme(); });
  1420. }
  1421. /* ---------- copiar comando ---------- */
  1422. function initCopy() {
  1423. const btn = document.getElementById('copyBtn');
  1424. if (!btn)
  1425. return;
  1426. btn.addEventListener('click', async () => {
  1427. const cmd = document.getElementById('installCmd').textContent;
  1428. copyText(cmd, btn);
  1429. });
  1430. const agentBtn = document.getElementById('agentCopyBtn');
  1431. if (agentBtn) {
  1432. agentBtn.addEventListener('click', async () => {
  1433. const cmd = document.getElementById('agentCmd').textContent;
  1434. copyText(cmd, agentBtn);
  1435. });
  1436. }
  1437. }
  1438. async function copyText(text, btn) {
  1439. try {
  1440. await navigator.clipboard.writeText(text);
  1441. }
  1442. catch {
  1443. const ta = document.createElement('textarea');
  1444. ta.value = text;
  1445. document.body.appendChild(ta);
  1446. ta.select();
  1447. document.execCommand('copy');
  1448. ta.remove();
  1449. }
  1450. const orig = t('misc.copy');
  1451. btn.textContent = t('misc.copied');
  1452. setTimeout(() => { btn.textContent = orig; }, 1600);
  1453. }
  1454. /* ---------- boot ---------- */
  1455. function initTrafficRanges() {
  1456. const wrap = document.getElementById('trafficRanges');
  1457. if (!wrap)
  1458. return;
  1459. wrap.addEventListener('click', (e) => {
  1460. const btn = e.target.closest('button[data-range]');
  1461. if (btn)
  1462. setTrafficRange(btn.dataset.range);
  1463. });
  1464. }
  1465. /* ---------- slider de capturas ---------- */
  1466. const SHOT_SLIDES = ['overview', 'routers', 'devices', 'topology', 'alerts', 'settings'];
  1467. const SHOT_ALT = {
  1468. overview: { es: 'Panel de NetPulse: salud, tráfico y dispositivos de la red', en: 'NetPulse overview: network health, traffic and devices' },
  1469. routers: { es: 'Vista de routers: flota, salud y métricas por router', en: 'Routers view: fleet, health and per-router metrics' },
  1470. devices: { es: 'Vista de dispositivos: clientes, banda y señal', en: 'Devices view: clients, band and signal' },
  1471. topology: { es: 'Topología: el mapa vivo de tu red, inferido del FDB', en: 'Topology: the live map of your network, inferred from the FDB' },
  1472. alerts: { es: 'Feed de alertas: lo que pasa en tu red, en vivo', en: 'Alerts feed: what happens in your network, live' },
  1473. settings: { es: 'Ajustes: apariencia, usuarios, routers y servicios', en: 'Settings: appearance, users, routers and services' },
  1474. };
  1475. let shotIndex = 0;
  1476. function shotUrl(view) {
  1477. const raw = (document.documentElement.lang || 'en').slice(0, 2);
  1478. const lang = (raw === 'es' || raw === 'en') ? raw : 'en'; // solo existen capturas es/en
  1479. const theme = document.documentElement.classList.contains('light') ? 'light' : 'dark';
  1480. return `/assets/shot-${view}-${lang}-${theme}.webp`;
  1481. }
  1482. // Capturas propias de una página estática: <img data-hashot="device"> se sirve
  1483. // en el idioma y el tema activos, igual que el carrusel de la portada.
  1484. function renderHashots() {
  1485. const raw = (document.documentElement.lang || 'en').slice(0, 2);
  1486. const lang = (raw === 'es' || raw === 'en') ? raw : 'en';
  1487. const theme = document.documentElement.classList.contains('light') ? 'light' : 'dark';
  1488. document.querySelectorAll('img[data-hashot]').forEach(img => {
  1489. img.src = `/assets/ha-${img.dataset.hashot}-${lang}-${theme}.webp`;
  1490. });
  1491. }
  1492. function renderShot(i) {
  1493. if (typeof i === 'number')
  1494. shotIndex = (i + SHOT_SLIDES.length) % SHOT_SLIDES.length;
  1495. const view = SHOT_SLIDES[shotIndex];
  1496. const img = document.getElementById('shotImg');
  1497. const cap = document.getElementById('shotCaption');
  1498. if (!img)
  1499. return;
  1500. const lang = (document.documentElement.lang || 'en').slice(0, 2);
  1501. img.src = shotUrl(view);
  1502. img.alt = (SHOT_ALT[view] && SHOT_ALT[view][lang]) || view;
  1503. // captura del hero: siempre la vista "overview", siguiendo idioma y tema
  1504. const hero = document.getElementById('heroShot');
  1505. if (hero) {
  1506. hero.src = shotUrl('overview');
  1507. hero.alt = (SHOT_ALT.overview && SHOT_ALT.overview[lang]) || 'NetPulse overview';
  1508. }
  1509. if (cap)
  1510. cap.textContent = t(`shots.s${shotIndex + 1}`);
  1511. document.querySelectorAll('#shotThumbs .thumb').forEach((th, idx) => {
  1512. th.classList.toggle('active', idx === shotIndex);
  1513. });
  1514. }
  1515. function initSlider() {
  1516. const img = document.getElementById('shotImg');
  1517. if (!img)
  1518. return;
  1519. document.querySelectorAll('#shotThumbs img[data-view]').forEach((el) => {
  1520. el.src = shotUrl(el.dataset.view);
  1521. });
  1522. document.getElementById('shotPrev').addEventListener('click', () => renderShot(shotIndex - 1));
  1523. document.getElementById('shotNext').addEventListener('click', () => renderShot(shotIndex + 1));
  1524. document.querySelectorAll('#shotThumbs .thumb').forEach((th) => {
  1525. th.addEventListener('click', () => renderShot(parseInt(th.dataset.slide, 10)));
  1526. });
  1527. renderShot(0);
  1528. }
  1529. /* ---------- lightbox de capturas ---------- */
  1530. function initLightbox() {
  1531. const lightbox = document.getElementById('lightbox');
  1532. const lightboxImg = document.getElementById('lightboxImg');
  1533. const lightboxCaption = document.getElementById('lightboxCaption');
  1534. const lightboxClose = document.getElementById('lightboxClose');
  1535. const lightboxPrev = document.getElementById('lightboxPrev');
  1536. const lightboxNext = document.getElementById('lightboxNext');
  1537. if (!lightbox || !lightboxImg)
  1538. return;
  1539. function syncLightbox() {
  1540. const src = shotUrl(SHOT_SLIDES[shotIndex]);
  1541. const lang = (document.documentElement.lang || 'en').slice(0, 2);
  1542. lightboxImg.src = src;
  1543. lightboxImg.alt = (SHOT_ALT[SHOT_SLIDES[shotIndex]] && SHOT_ALT[SHOT_SLIDES[shotIndex]][lang]) || SHOT_SLIDES[shotIndex];
  1544. lightboxCaption.textContent = t(`shots.s${shotIndex + 1}`);
  1545. }
  1546. function openLightbox(img) {
  1547. shotIndex = SHOT_SLIDES.indexOf(img.dataset.view) >= 0 ? SHOT_SLIDES.indexOf(img.dataset.view) : shotIndex;
  1548. syncLightbox();
  1549. lightbox.hidden = false;
  1550. lightbox.setAttribute('aria-hidden', 'false');
  1551. if (lightboxClose)
  1552. lightboxClose.focus();
  1553. document.body.style.overflow = 'hidden';
  1554. }
  1555. function closeLightbox() {
  1556. lightbox.hidden = true;
  1557. lightbox.setAttribute('aria-hidden', 'true');
  1558. document.body.style.overflow = '';
  1559. }
  1560. function nav(dir) {
  1561. renderShot(shotIndex + dir);
  1562. syncLightbox();
  1563. }
  1564. document.querySelectorAll('img[data-shot]').forEach((img) => {
  1565. img.addEventListener('click', () => openLightbox(img));
  1566. });
  1567. if (lightboxClose)
  1568. lightboxClose.addEventListener('click', closeLightbox);
  1569. if (lightboxPrev)
  1570. lightboxPrev.addEventListener('click', () => nav(-1));
  1571. if (lightboxNext)
  1572. lightboxNext.addEventListener('click', () => nav(1));
  1573. lightbox.addEventListener('click', (e) => { if (e.target === lightbox)
  1574. closeLightbox(); });
  1575. document.addEventListener('keydown', (e) => {
  1576. if (lightbox.hidden)
  1577. return;
  1578. if (e.key === 'Escape')
  1579. closeLightbox();
  1580. if (e.key === 'ArrowLeft')
  1581. nav(-1);
  1582. if (e.key === 'ArrowRight')
  1583. nav(1);
  1584. });
  1585. }
  1586. /* ---------- badges de GitHub (stars + última release) ---------- */
  1587. /* fail-silent: si no hay red o la API limita, los chips quedan ocultos */
  1588. async function initGhMeta() {
  1589. const show = (id, text) => {
  1590. const el = document.getElementById(id);
  1591. if (!el)
  1592. return;
  1593. el.querySelector('[data-n]').textContent = text;
  1594. el.hidden = false;
  1595. };
  1596. try {
  1597. const r = await fetch('https://api.github.com/repos/gnacho/netpulse', { headers: { Accept: 'application/vnd.github+json' } });
  1598. if (r.ok) {
  1599. const d = await r.json();
  1600. if (typeof d.stargazers_count === 'number') {
  1601. show('ghStars', `★ ${d.stargazers_count}`);
  1602. const nav = document.getElementById('navStar');
  1603. const c = nav && nav.querySelector('[data-n]');
  1604. if (c) {
  1605. c.textContent = d.stargazers_count;
  1606. c.hidden = false;
  1607. }
  1608. }
  1609. }
  1610. const rel = await fetch('https://api.github.com/repos/gnacho/netpulse/releases/latest', { headers: { Accept: 'application/vnd.github+json' } });
  1611. if (rel.ok) {
  1612. const rd = await rel.json();
  1613. if (rd.tag_name)
  1614. show('ghRel', rd.tag_name);
  1615. }
  1616. }
  1617. catch { /* sin red */ }
  1618. }
  1619. document.addEventListener('DOMContentLoaded', () => {
  1620. initAppearance();
  1621. initBackgroundCanvas();
  1622. renderTicker();
  1623. renderAlerts();
  1624. initReveals();
  1625. initTheater();
  1626. initCopy();
  1627. initTrafficRanges();
  1628. initSlider();
  1629. initLightbox();
  1630. heroCountUps();
  1631. initGhMeta();
  1632. });