app.js 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  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) { el.textContent = format ? format(target) : target.toFixed(decimals) + suffix; return }
  23. const start = performance.now()
  24. function frame(now) {
  25. const p = Math.min(1, (now - start) / duration)
  26. const v = target * easeOutCubic(p)
  27. el.textContent = format ? format(v) : v.toFixed(decimals) + suffix
  28. if (p < 1) requestAnimationFrame(frame)
  29. }
  30. requestAnimationFrame(frame)
  31. }
  32. function fmtLocale(n, decimals = 0) {
  33. return n.toLocaleString(CURRENT === 'en' ? 'en-US' : CURRENT, {
  34. minimumFractionDigits: decimals, maximumFractionDigits: decimals,
  35. })
  36. }
  37. function mkSvgEl(tag, attrs = {}, parent) {
  38. const e = document.createElementNS('http://www.w3.org/2000/svg', tag)
  39. Object.entries(attrs).forEach(([k, v]) => e.setAttribute(k, v))
  40. if (parent) parent.appendChild(e)
  41. return e
  42. }
  43. /* ---------- fondo netflow (ondas de tráfico, calmado) ---------- */
  44. function mulberry32(seed) {
  45. let a = seed >>> 0
  46. return function () {
  47. a |= 0; a = (a + 0x6D2B79F5) | 0
  48. let t = Math.imul(a ^ (a >>> 15), 1 | a)
  49. t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
  50. return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  51. }
  52. }
  53. function initBackgroundCanvas() {
  54. const canvas = document.getElementById('bgCanvas')
  55. if (!canvas) return
  56. const ctx = canvas.getContext('2d')
  57. const reduce = reduceMotion
  58. const dpr = Math.min(window.devicePixelRatio || 1, 2)
  59. let w = 0, h = 0
  60. let layers = []
  61. const rand = mulberry32(0x51A7E)
  62. const alphaColor = (c, a) => c.replace(')', ` / ${a})`)
  63. function buildLayers() {
  64. const palette = ['accent', 'tunnel', 'ok']
  65. layers = palette.map((color, i) => ({
  66. color,
  67. base: 0.55 + i * 0.17,
  68. amp: 22 + rand() * 26,
  69. freq: 0.004 + rand() * 0.0025,
  70. speed: 0.00006 + rand() * 0.00009,
  71. phase: rand() * Math.PI * 2,
  72. peak: 0.08 + rand() * 0.035,
  73. drift: 6 + rand() * 10,
  74. }))
  75. }
  76. function sample(l, x, t) {
  77. return Math.sin(x * l.freq + t * l.speed + l.phase) * l.amp * 0.62
  78. + Math.sin(x * l.freq * 0.51 + t * l.speed * 0.73 + l.phase * 1.7) * l.amp * 0.38
  79. }
  80. function render(t) {
  81. ctx.clearRect(0, 0, w, h)
  82. const span = 8
  83. for (const l of layers) {
  84. const base = l.base * h + Math.sin(t * 0.00005 + l.phase * 2) * l.drift
  85. const col = getCssVar(l.color)
  86. // banda: de la onda hasta el fondo, con degradado que se desvanece hacia abajo
  87. const g = ctx.createLinearGradient(0, base, 0, h)
  88. g.addColorStop(0, alphaColor(col, l.peak))
  89. g.addColorStop(0.5, alphaColor(col, l.peak * 0.35))
  90. g.addColorStop(1, alphaColor(col, 0))
  91. ctx.beginPath()
  92. ctx.moveTo(-span, base + sample(l, -span, t))
  93. for (let x = 0; x <= w + span; x += span) ctx.lineTo(x, base + sample(l, x, t))
  94. ctx.lineTo(w + span, h + 20)
  95. ctx.lineTo(-span, h + 20)
  96. ctx.closePath()
  97. ctx.fillStyle = g
  98. ctx.fill()
  99. // línea de la onda (definición sutil)
  100. ctx.beginPath()
  101. ctx.moveTo(-span, base + sample(l, -span, t))
  102. for (let x = 0; x <= w + span; x += span) ctx.lineTo(x, base + sample(l, x, t))
  103. ctx.strokeStyle = alphaColor(col, l.peak * 0.6)
  104. ctx.lineWidth = 1.2
  105. ctx.stroke()
  106. }
  107. }
  108. function resize() {
  109. w = window.innerWidth
  110. h = window.innerHeight
  111. canvas.width = Math.round(w * dpr)
  112. canvas.height = Math.round(h * dpr)
  113. ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
  114. buildLayers()
  115. if (reduce) render(0)
  116. }
  117. resize()
  118. window.addEventListener('resize', resize)
  119. if (reduce) return
  120. function loop(now) {
  121. render(now / 1000)
  122. requestAnimationFrame(loop)
  123. }
  124. requestAnimationFrame(loop)
  125. }
  126. /* ---------- count-up hero ---------- */
  127. function heroCountUps() {
  128. document.querySelectorAll('#heroStrip [data-count]').forEach(el => {
  129. const target = parseFloat(el.dataset.count)
  130. const decimals = parseInt(el.dataset.decimals || '0', 10)
  131. const suffix = el.dataset.suffix || ''
  132. animateNumber(el, target, { decimals, suffix, duration: 1400 })
  133. })
  134. }
  135. /* ---------- ticker ---------- */
  136. function renderTicker() {
  137. const el = document.getElementById('ticker')
  138. if (!el) return
  139. const items = [
  140. `<span><i class="dot" style="background:rgb(var(--ok))"></i><i>${t('strip.health')}</i>&nbsp;<i class="font-mono">92/100</i></span>`,
  141. `<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>`,
  142. `<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>`,
  143. `<span><i class="dot" style="background:rgb(var(--info))"></i><i>${t('strip.latency')}</i>&nbsp;<i class="font-mono">8 ms</i></span>`,
  144. `<span><i class="dot" style="background:rgb(var(--text-secondary))"></i><i>${t('strip.devices')}</i>&nbsp;<i class="font-mono">65</i></span>`,
  145. `<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>`,
  146. `<span><i class="dot" style="background:rgb(var(--warn))"></i><i>DNS</i>&nbsp;<i class="font-mono">14 ms</i></span>`,
  147. `<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>`,
  148. ]
  149. el.innerHTML = items.join('') + items.join('')
  150. }
  151. /* ---------- stage 0: health ring ---------- */
  152. let ringPlayed = false
  153. function playRing() {
  154. if (ringPlayed) return
  155. ringPlayed = true
  156. const arc = document.getElementById('ringArc')
  157. const num = document.getElementById('ringNum')
  158. const C = 590.6
  159. const score = DEMO.score
  160. if (reduceMotion) { arc.style.strokeDashoffset = C * (1 - score / 100); num.textContent = score; return }
  161. const dur = 1300
  162. const start = performance.now()
  163. function frame(now) {
  164. const p = Math.min(1, (now - start) / dur)
  165. const e = easeOutCubic(p)
  166. const v = score * e
  167. num.textContent = Math.round(v)
  168. arc.style.strokeDashoffset = C * (1 - v / 100)
  169. if (p < 1) requestAnimationFrame(frame)
  170. }
  171. requestAnimationFrame(frame)
  172. }
  173. /* ---------- stage 1: traffic chart ---------- */
  174. let trafficPlayed = false
  175. let trafficTimer = null
  176. function genSeries(n, base, amp, seed = 1) {
  177. const out = []; let s = seed
  178. for (let i = 0; i < n; i++) {
  179. s = (s * 9301 + 49297) % 233280
  180. const noise = s / 233280
  181. out.push(Math.max(2, base + Math.sin(i / 4) * amp * 0.6 + noise * amp))
  182. }
  183. return out
  184. }
  185. function pathFrom(data, W, H, max) {
  186. const step = W / (data.length - 1)
  187. return data.map((v, i) => `${i === 0 ? 'M' : 'L'}${(i * step).toFixed(1)} ${(H - (v / max) * (H - 10) - 5).toFixed(1)}`).join(' ')
  188. }
  189. function playTraffic() {
  190. if (trafficPlayed) return
  191. trafficPlayed = true
  192. const W = 480, H = 160
  193. const downData = genSeries(52, DEMO.down, 22, 7)
  194. const upData = genSeries(52, DEMO.up, 6, 13)
  195. const max = 120
  196. const lineDown = document.getElementById('lineDown')
  197. const lineUp = document.getElementById('lineUp')
  198. const areaDown = document.getElementById('areaDown')
  199. const dPath = pathFrom(downData, W, H, max)
  200. const uPath = pathFrom(upData, W, H, max)
  201. lineDown.setAttribute('d', dPath)
  202. lineUp.setAttribute('d', uPath)
  203. areaDown.setAttribute('d', dPath + ` L${W} ${H} L0 ${H} Z`)
  204. if (reduceMotion) {
  205. areaDown.setAttribute('opacity', '1')
  206. document.getElementById('wanDown').textContent = DEMO.down.toFixed(1)
  207. document.getElementById('wanUp').textContent = DEMO.up.toFixed(1)
  208. document.getElementById('wanLat').textContent = DEMO.latency
  209. return
  210. }
  211. const Ld = lineDown.getTotalLength()
  212. const Lu = lineUp.getTotalLength()
  213. lineDown.style.strokeDasharray = Ld
  214. lineUp.style.strokeDasharray = Lu
  215. lineDown.style.strokeDashoffset = Ld
  216. lineUp.style.strokeDashoffset = Lu
  217. const start = performance.now()
  218. const dur = 1500
  219. function frame(now) {
  220. const p = Math.min(1, (now - start) / dur)
  221. const e = easeOutCubic(p)
  222. lineDown.style.strokeDashoffset = Ld * (1 - e)
  223. lineUp.style.strokeDashoffset = Lu * (1 - e)
  224. areaDown.setAttribute('opacity', String(e * 0.9))
  225. if (p < 1) requestAnimationFrame(frame)
  226. else startLiveJitter()
  227. }
  228. requestAnimationFrame(frame)
  229. animateNumber(document.getElementById('wanDown'), DEMO.down, { decimals: 1, duration: 1400 })
  230. animateNumber(document.getElementById('wanUp'), DEMO.up, { decimals: 1, duration: 1400 })
  231. animateNumber(document.getElementById('wanLat'), DEMO.latency, { duration: 1400 })
  232. }
  233. function startLiveJitter() {
  234. if (trafficTimer) return
  235. const downEl = document.getElementById('wanDown')
  236. const upEl = document.getElementById('wanUp')
  237. trafficTimer = setInterval(() => {
  238. if (!downEl.isConnected) return
  239. const d = Math.max(55, DEMO.down + (Math.random() - 0.5) * 7)
  240. const u = Math.max(9, DEMO.up + (Math.random() - 0.5) * 2.5)
  241. downEl.textContent = d.toFixed(1)
  242. upEl.textContent = u.toFixed(1)
  243. }, 2600)
  244. }
  245. /* ---------- stage 2: topologia fiel a la app (model.ts + TopologyMap.tsx) ---------- */
  246. let topoBuilt = false
  247. let routersBuilt = false
  248. let routersPlayed = false
  249. /* ===== datos demo canonicos (demo-canon.json, D65-1) ===== */
  250. 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"}
  251. const DEMO_WG = {
  252. interface: 'wg0', subnet: '10.0.0.1/24', status: 'active',
  253. peers: [
  254. {"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"},
  255. {"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"},
  256. {"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"},
  257. {"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"},
  258. {"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"},
  259. ],
  260. }
  261. const DEMO_DISTRIBUTION = [
  262. {"id":"dist-flint2-lan3","kind":"inferred","routerId":"flint2","port":"lan3","macCount":8},
  263. {"id":"dist-pve","kind":"hypervisor","routerId":"flint2","port":"lan5","macCount":11,"hostDeviceId":"pve","name":"Proxmox pve"},
  264. {"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"}},
  265. ]
  266. const DEMO_DEVICES = [
  267. {"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},
  268. {"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},
  269. {"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},
  270. {"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},
  271. {"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"},
  272. {"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},
  273. {"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},
  274. {"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},
  275. {"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"},
  276. {"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},
  277. {"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},
  278. {"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},
  279. {"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"},
  280. {"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"},
  281. {"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},
  282. {"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},
  283. {"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},
  284. {"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},
  285. {"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},
  286. {"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},
  287. {"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},
  288. {"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},
  289. {"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},
  290. {"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},
  291. {"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},
  292. {"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},
  293. {"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},
  294. {"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},
  295. {"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},
  296. {"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},
  297. {"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},
  298. {"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},
  299. {"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},
  300. {"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},
  301. {"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},
  302. {"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},
  303. {"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},
  304. {"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},
  305. {"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},
  306. {"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},
  307. {"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},
  308. {"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},
  309. {"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},
  310. {"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},
  311. {"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"}},
  312. {"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"},
  313. {"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"},
  314. {"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"},
  315. {"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"},
  316. {"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"},
  317. {"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"},
  318. {"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"},
  319. {"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"},
  320. {"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"},
  321. {"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"},
  322. {"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"},
  323. {"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"},
  324. {"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"},
  325. {"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"},
  326. {"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"},
  327. {"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"},
  328. {"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"},
  329. {"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"},
  330. {"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"},
  331. {"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"},
  332. ]
  333. const DEMO_ROUTERS = [
  334. {"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]},
  335. {"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"}},
  336. {"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"}},
  337. {"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]},
  338. ]
  339. /* ===== utilidades de geometria (de model.ts) ===== */
  340. const VB_W = 1000, VB_H = 680
  341. const GATEWAY_COORD = { x: 500, y: 250, r: 40, label: { x: 446, y: 312, anchor: 'end' } }
  342. const AP_COORDS = [
  343. { x: 195, y: 470, r: 32, label: { x: 124, y: 464, anchor: 'end' } },
  344. { x: 500, y: 505, r: 32, label: { x: 554, y: 500, anchor: 'start' } },
  345. { x: 805, y: 470, r: 32, label: { x: 858, y: 464, anchor: 'start' } },
  346. ]
  347. const INTERNET_COORD = { x: 500, y: 58 }
  348. const PEER_COORDS = [{ x: 265, y: 26 }, { x: 735, y: 26 }, { x: 140, y: 26 }, { x: 860, y: 26 }]
  349. const PEERS_OVERFLOW_COORD = { x: 560, y: 26 }
  350. const UPLINK_PATHS = [
  351. { d: 'M 464 282 C 390 340, 290 400, 224 440', lx: 292, ly: 366 },
  352. { d: 'M 500 292 C 500 360, 500 420, 500 468', lx: 514, ly: 418 },
  353. { d: 'M 536 282 C 610 340, 710 400, 776 440', lx: 664, ly: 366 },
  354. ]
  355. const WG_PATHS = [
  356. { d: 'M 272 44 C 330 82, 410 94, 474 80', dur: 3 },
  357. { d: 'M 728 44 C 670 82, 590 94, 526 80', dur: 3.4 },
  358. ]
  359. const GATEWAY_RINGS = [{ r: 96, cap: 5 }, { r: 130, cap: 8 }]
  360. const AP_RINGS = [{ r: 82, cap: 7 }, { r: 120, cap: 13 }]
  361. const GW_EAST_FAN = [336, 24]
  362. const GW_WEST_FAN = [150, 210]
  363. const AP_WIRED_FAN = [50, 130]
  364. const DIST_FAN_RADIUS = 96
  365. const DIST_FAN_MAX = 5
  366. const DIST_RINGS = [{ r: 72, cap: 7 }, { r: 118, cap: 12 }]
  367. const HUB_FAN_RADIUS = 68
  368. const ROUTER_FAN_RADIUS = 150
  369. const HYPERVISOR_FAN_RADIUS = 320
  370. const CT_COLS = 5, CT_DX = 46, CT_DY = 44, CT_OFFSET_Y = 64
  371. const GW_GRID_MIN = 6, GW_GRID_ROWS = 4, GW_GRID_DX = 56, GW_GRID_DY = 50, GW_GRID_R0 = 160
  372. const TOPO_COLOR = { accent: '#22D3EE', tunnel: '#A78BFA', ok: '#34D399', warn: '#FBBF24', danger: '#F87171', info: '#60A5FA' }
  373. function bandColor(band, weak) { if (weak) return TOPO_COLOR.warn; if (band === '5 GHz') return TOPO_COLOR.accent; if (band === '2.4 GHz') return TOPO_COLOR.info; return TOPO_COLOR.ok }
  374. function statusColor(s) { if (s === 'warn') return TOPO_COLOR.warn; if (s === 'offline') return TOPO_COLOR.danger; return TOPO_COLOR.ok }
  375. function linkColor(k, wifi) { if (k === 'wg') return TOPO_COLOR.tunnel; if (k === 'uplink' && wifi) return TOPO_COLOR.warn; return TOPO_COLOR.ok }
  376. 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) } }
  377. const rad = (d) => (d * Math.PI) / 180
  378. const norm = (a) => ((a % 360) + 360) % 360
  379. function angleTo(x, y, tx, ty) { return norm((Math.atan2(ty - y, tx - x) * 180) / Math.PI) }
  380. 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 } }
  381. function arcAround(center, half) { const s = norm(center - half); const e = norm(center + half); return s <= e ? [[s, e]] : [[s, 360], [0, e]] }
  382. function freeArcs(excludes) {
  383. 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])
  384. const free = []; let cur = 0
  385. for (const [s, e] of ex) { if (s > cur) free.push([cur, s]); cur = Math.max(cur, e) }
  386. if (cur < 360) free.push([cur, 360])
  387. return free
  388. }
  389. function ringLayout(items, node, rings, excludes) {
  390. const free = freeArcs(excludes); const total = free.reduce((a, [s, e]) => a + (e - s), 0)
  391. if (total <= 0) return
  392. let idx = 0
  393. for (const ring of rings) {
  394. if (idx >= items.length) break
  395. const n = Math.min(ring.cap, items.length - idx)
  396. let placed = 0
  397. for (let ai = 0; ai < free.length && placed < n; ai++) {
  398. const [s, e] = free[ai]
  399. let k = Math.min(Math.round((n * (e - s)) / total), n - placed)
  400. if (ai === free.length - 1) k = n - placed
  401. for (let i = 0; i < k; i++) {
  402. const a = s + ((e - s) * (i + 0.5)) / k
  403. const p = pos(node.x, node.y, a, ring.r)
  404. Object.assign(items[idx++], p); placed++
  405. }
  406. }
  407. }
  408. }
  409. function fanLayout(items, node, r, a0, a1) {
  410. if (a1 < a0) a1 += 360
  411. const n = items.length
  412. 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)) })
  413. }
  414. function gridLayoutWest(items, node) {
  415. items.forEach((d, i) => {
  416. const col = Math.floor(i / GW_GRID_ROWS), row = i % GW_GRID_ROWS
  417. const inThisCol = Math.min(GW_GRID_ROWS, items.length - col * GW_GRID_ROWS)
  418. d.x = node.x - GW_GRID_R0 - col * GW_GRID_DX
  419. d.y = node.y + (row - (inThisCol - 1) / 2) * GW_GRID_DY
  420. })
  421. }
  422. function subtreeTraffic(childrenOf, hubId, seen = new Set()) {
  423. if (seen.has(hubId)) return 0
  424. seen.add(hubId)
  425. let sum = 0
  426. for (const d of childrenOf(hubId)) { sum += d.trafficMbps + subtreeTraffic(childrenOf, d.id, seen) }
  427. return sum
  428. }
  429. /* ===== builder de modelo (simplificado: sin semantica server-side) ===== */
  430. function buildTopologyModel({ routers, devices, wan, wireguard, distributionNodes = [] }) {
  431. const gateway = routers.find((r) => r.roleBadge === 'Principal') || routers[0]
  432. const aps = routers.filter((r) => r.id !== gateway.id).slice(0, AP_COORDS.length)
  433. const gatewayNode = gateway ? { kind: 'router', id: gateway.id, router: gateway, ...GATEWAY_COORD } : null
  434. const apNodes = aps.map((router, i) => ({ kind: 'router', id: router.id, router, ...AP_COORDS[i] }))
  435. const routerNodes = gatewayNode ? [gatewayNode, ...apNodes] : apNodes
  436. const routerById = new Map(routerNodes.map((n) => [n.id, n]))
  437. const internetNode = { id: 'internet', ...INTERNET_COORD }
  438. const managedMacs = new Set(distributionNodes.filter((n) => n.kind === 'managed' && n.mac).map((n) => n.mac.toUpperCase()))
  439. const online = devices.filter((d) => d.online && !managedMacs.has(d.mac.toUpperCase()))
  440. const deviceById = new Map(online.map((d) => [d.id, d]))
  441. const distById = new Map(distributionNodes.map((n) => [n.id, n]))
  442. const hubOf = (d) => {
  443. if (d.attachTo && (routerById.has(d.attachTo) || distById.has(d.attachTo) || deviceById.has(d.attachTo))) return d.attachTo
  444. if (isWired(d) && !d.port && gatewayNode) return gatewayNode.id
  445. return d.routerId
  446. }
  447. const isWired = (d) => d.band === 'cable'
  448. const childrenOf = (hubId) => online.filter((d) => hubOf(d) === hubId)
  449. const deviceHubs = new Set()
  450. for (const d of online) { if (d.attachTo && deviceById.has(d.attachTo)) deviceHubs.add(d.attachTo) }
  451. const distNodes = []
  452. const anchorPos = new Map()
  453. const fanArcByRouter = new Map()
  454. const hypervisorHosts = new Set(distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId).map((n) => n.hostDeviceId))
  455. for (const node of routerNodes) {
  456. const isGw = node.id === gatewayNode?.id
  457. const dists = distributionNodes.filter((n) => n.routerId === node.id && (n.kind === 'inferred' || n.kind === 'managed'))
  458. const directWired = childrenOf(node.id).filter((d) => isWired(d))
  459. const hubs = directWired.filter((d) => deviceHubs.has(d.id))
  460. const plain = directWired.filter((d) => !deviceHubs.has(d.id))
  461. const anchors = [
  462. ...dists.map((n) => ({ id: n.id, kind: 'dist', ref: n })),
  463. ...hubs.map((d) => ({ id: d.id, kind: 'hub', ref: d })),
  464. ...plain.map((d) => ({ id: d.id, kind: 'dev', ref: d })),
  465. ]
  466. if (anchors.length === 0) continue
  467. const placed = []
  468. if (isGw) {
  469. const east = anchors.filter((a) => a.kind === 'dist')
  470. const farWest = anchors.filter((a) => a.kind === 'hub' && hypervisorHosts.has(a.id))
  471. const west = anchors.filter((a) => a.kind !== 'dist' && !farWest.includes(a))
  472. const eastItems = east.map((a) => ({ ...a, x: 0, y: 0 }))
  473. const farWestItems = farWest.map((a) => ({ ...a, x: 0, y: 0 }))
  474. const westItems = west.map((a) => ({ ...a, x: 0, y: 0 }))
  475. fanLayout(eastItems, node, ROUTER_FAN_RADIUS, GW_EAST_FAN[0], GW_EAST_FAN[1])
  476. fanLayout(farWestItems, node, HYPERVISOR_FAN_RADIUS, 160, 200)
  477. if (westItems.length >= GW_GRID_MIN) gridLayoutWest(westItems, node)
  478. else fanLayout(westItems, node, ROUTER_FAN_RADIUS, GW_WEST_FAN[0], GW_WEST_FAN[1])
  479. placed.push(...eastItems, ...farWestItems, ...westItems)
  480. fanArcByRouter.set(node.id, [...arcAround(0, 26), [GW_WEST_FAN[0] - 8, GW_WEST_FAN[1] + 8]])
  481. } else {
  482. const items = anchors.map((a) => ({ ...a, x: 0, y: 0 }))
  483. fanLayout(items, node, ROUTER_FAN_RADIUS, AP_WIRED_FAN[0], AP_WIRED_FAN[1])
  484. placed.push(...items)
  485. fanArcByRouter.set(node.id, [[AP_WIRED_FAN[0] - 8, AP_WIRED_FAN[1] + 8]])
  486. }
  487. for (const p of placed) {
  488. anchorPos.set(p.id, { x: p.x, y: p.y })
  489. if (p.kind === 'dist') distNodes.push({ kind: 'dist', id: p.ref.id, node: p.ref, x: p.x, y: p.y, r: 20 })
  490. }
  491. }
  492. const chips = []
  493. const mkChip = (d, hubId, isCt = false) => ({
  494. kind: 'chip', id: d.id, device: d, x: 0, y: 0,
  495. size: isWired(d) ? 26 : 24, wired: isWired(d), band: d.band,
  496. weak: d.signalDbm != null && d.signalDbm <= -65, hubId, isCt,
  497. })
  498. const ringRadii = new Map()
  499. for (const node of routerNodes) {
  500. const isGw = node.id === gatewayNode?.id
  501. const wifi = childrenOf(node.id).filter((d) => !isWired(d)).map((d) => mkChip(d, node.id))
  502. if (wifi.length === 0) continue
  503. const excludes = []
  504. if (isGw) {
  505. excludes.push(...arcAround(270, 14))
  506. if (gatewayNode) excludes.push(...arcAround(angleTo(gatewayNode.x, gatewayNode.y, gatewayNode.label.x, gatewayNode.label.y), 22))
  507. for (const ap of apNodes) excludes.push(...arcAround(angleTo(node.x, node.y, ap.x, ap.y), 15))
  508. } else {
  509. if (gatewayNode) excludes.push(...arcAround(angleTo(node.x, node.y, gatewayNode.x, gatewayNode.y), 27))
  510. excludes.push(...arcAround(angleTo(node.x, node.y, node.label.x, node.label.y), 22))
  511. }
  512. excludes.push(...(fanArcByRouter.get(node.id) || []))
  513. const baseRings = isGw ? GATEWAY_RINGS : AP_RINGS
  514. const rings = [...baseRings]
  515. let cap = rings.reduce((a, r) => a + r.cap, 0)
  516. while (cap < wifi.length) { const last = rings[rings.length - 1]; rings.push({ r: last.r + 30, cap: last.cap + 5 }); cap = rings.reduce((a, r) => a + r.cap, 0) }
  517. ringRadii.set(node.id, rings.map((r) => r.r))
  518. ringLayout(wifi, node, rings, excludes)
  519. wifi.forEach((c, i) => { if (i >= baseRings[0].cap) c.size = 22 })
  520. chips.push(...wifi)
  521. }
  522. for (const node of routerNodes) {
  523. for (const d of childrenOf(node.id).filter(isWired)) {
  524. if (deviceHubs.has(d.id)) continue
  525. const p = anchorPos.get(d.id); if (!p) continue
  526. const c = mkChip(d, node.id); Object.assign(c, p); chips.push(c)
  527. }
  528. }
  529. const hubChips = []
  530. for (const hubId of deviceHubs) {
  531. const hubDev = deviceById.get(hubId); if (!hubDev) continue
  532. const parentHub = hubOf(hubDev)
  533. const p = anchorPos.get(hubId); if (!p) continue
  534. const hc = mkChip(hubDev, parentHub); Object.assign(hc, p); hubChips.push(hc)
  535. const kids = hypervisorHosts.has(hubId) ? [] : childrenOf(hubId).map((d) => mkChip(d, hubId))
  536. const center = angleTo((routerById.get(parentHub) || p).x, (routerById.get(parentHub) || p).y, p.x, p.y)
  537. fanLayout(kids, p, HUB_FAN_RADIUS, center - 45, center + 45)
  538. chips.push(...kids)
  539. }
  540. chips.push(...hubChips)
  541. for (const dv of distNodes) {
  542. const kids = childrenOf(dv.id).map((d) => mkChip(d, dv.id))
  543. const rn = routerById.get(dv.node.routerId)
  544. const center = rn ? angleTo(rn.x, rn.y, dv.x, dv.y) : 0
  545. if (kids.length > DIST_FAN_MAX) {
  546. const excludes = rn ? arcAround(angleTo(dv.x, dv.y, rn.x, rn.y), 20) : []
  547. const rings = [...DIST_RINGS]
  548. let cap = rings.reduce((a, r) => a + r.cap, 0)
  549. while (cap < kids.length) { const last = rings[rings.length - 1]; rings.push({ r: last.r + 34, cap: last.cap + 5 }); cap = rings.reduce((a, r) => a + r.cap, 0) }
  550. ringLayout(kids, dv, rings, excludes)
  551. } else {
  552. fanLayout(kids, dv, DIST_FAN_RADIUS, center - 68, center + 68)
  553. }
  554. chips.push(...kids)
  555. }
  556. const ctsByHost = new Map(), ctCountByHost = new Map()
  557. for (const dn of distributionNodes.filter((n) => n.kind === 'hypervisor' && n.hostDeviceId)) {
  558. const hostId = dn.hostDeviceId
  559. const hostChip = chips.find((c) => c.id === hostId)
  560. const kids = childrenOf(hostId).map((d) => mkChip(d, hostId, true))
  561. if (!hostChip || kids.length === 0) continue
  562. 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 })
  563. ctsByHost.set(hostId, kids); ctCountByHost.set(hostId, kids.length)
  564. chips.push(...kids)
  565. }
  566. const ringOverflowChips = []
  567. const activePeers = wireguard.peers.filter((p) => p.active)
  568. const peerNodes = activePeers.slice(0, PEER_COORDS.length).map((peer, i) => ({ kind: 'peer', id: `peer-${peer.id}`, peer, ...PEER_COORDS[i] }))
  569. const hiddenPeers = activePeers.slice(PEER_COORDS.length)
  570. const chipById = new Map(chips.map((c) => [c.id, c]))
  571. const hubPos = (hubId) => {
  572. const rn = routerById.get(hubId); if (rn) return { x: rn.x, y: rn.y, r: rn.r }
  573. const dv = distNodes.find((n) => n.id === hubId); if (dv) return { x: dv.x, y: dv.y, r: dv.r }
  574. const c = chipById.get(hubId); if (c) return { x: c.x, y: c.y, r: c.size / 2 }
  575. return null
  576. }
  577. const links = []
  578. if (gatewayNode) {
  579. links.push({
  580. id: 'wan', kind: 'wan',
  581. d: 'M 500 92 C 500 122, 500 162, 500 208',
  582. lx: 518, ly: 162, label: `Fibra ${wan.plan} · ${wan.latencyMs} ms`,
  583. width: 3, ...flowFor(600), from: 'internet', to: gatewayNode.id,
  584. })
  585. }
  586. apNodes.forEach((node, i) => {
  587. const p = UPLINK_PATHS[i]
  588. const isWifi = node.router.backhaul === 'wifi'
  589. const traffic = subtreeTraffic(childrenOf, node.id)
  590. const label = isWifi ? 'WiFi uplink' : `Cable 1G${node.router.lldp ? ' · LLDP' : ''}`
  591. links.push({
  592. id: `uplink-${node.id}`, kind: 'uplink', wifi: isWifi,
  593. d: p.d, lx: p.lx, ly: p.ly, label,
  594. width: isWifi ? 2 : 3, ...flowFor(Math.max(traffic, isWifi ? 40 : 120)),
  595. from: gatewayNode?.id || 'internet', to: node.id,
  596. })
  597. })
  598. for (const dv of distNodes) {
  599. const rn = routerById.get(dv.node.routerId); if (!rn) continue
  600. const edge = pos(rn.x, rn.y, angleTo(rn.x, rn.y, dv.x, dv.y), rn.r + 2)
  601. const mid = { x: (edge.x + dv.x) / 2, y: (edge.y + dv.y) / 2 }
  602. links.push({
  603. id: `dist-${dv.id}`, kind: 'dist',
  604. d: `M ${edge.x} ${edge.y} Q ${mid.x + 6} ${mid.y - 6}, ${dv.x} ${dv.y}`,
  605. lx: 0, ly: 0, label: '',
  606. width: 2.5, ...flowFor(subtreeTraffic(childrenOf, dv.id), true),
  607. from: dv.node.routerId, to: dv.id,
  608. })
  609. }
  610. for (const chip of chips) {
  611. if (chip.isCt || !chip.wired) continue
  612. const hub = hubPos(chip.hubId); if (!hub) continue
  613. const a = angleTo(hub.x, hub.y, chip.x, chip.y)
  614. const edge = pos(hub.x, hub.y, a, hub.r + 2)
  615. const dx = chip.x - edge.x, dy = chip.y - edge.y
  616. const c1x = edge.x + dx * 0.5 - dy * 0.1
  617. const c1y = edge.y + dy * 0.5 + dx * 0.1
  618. const mbps = deviceHubs.has(chip.id) ? chip.device.trafficMbps + subtreeTraffic(childrenOf, chip.id) : chip.device.trafficMbps
  619. links.push({
  620. id: `wired-${chip.id}`, kind: 'wired',
  621. d: `M ${edge.x} ${edge.y} Q ${c1x} ${c1y}, ${chip.x} ${chip.y}`,
  622. lx: 0, ly: 0, label: '',
  623. width: 1.4, ...flowFor(mbps, true),
  624. from: chip.hubId, to: chip.id,
  625. })
  626. }
  627. for (const [hostId, cts] of ctsByHost) {
  628. const hostChip = chipById.get(hostId); if (!hostChip) continue
  629. for (const ct of cts) {
  630. links.push({
  631. id: `wired-${ct.id}`, kind: 'wired',
  632. d: `M ${hostChip.x} ${hostChip.y + hostChip.size / 2} L ${ct.x} ${ct.y - ct.size / 2}`,
  633. lx: 0, ly: 0, label: '',
  634. width: 1.2, ...flowFor(ct.device.trafficMbps, true),
  635. from: hostId, to: ct.id,
  636. })
  637. }
  638. }
  639. peerNodes.forEach((node, i) => {
  640. const p = WG_PATHS[i] || { d: '', dur: 3.2 }
  641. 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}`
  642. links.push({
  643. id: `wg-${node.peer.id}`, kind: 'wg',
  644. d, lx: 0, ly: 0, label: '',
  645. width: 2, packets: 1, packetDur: p.dur,
  646. from: node.id, to: 'internet',
  647. })
  648. })
  649. return {
  650. gatewayNode, apNodes, routerNodes, internetNode, peerNodes, hiddenPeers,
  651. chips, distNodes, ctsByHost, ctCountByHost, ringRadii, ringOverflowChips, links,
  652. wan,
  653. }
  654. }
  655. /* ===== iconos SVG inline ===== */
  656. function drawIcon(type, size, parent) {
  657. const s = size || 14
  658. const half = s / 2
  659. const scale = s / 24
  660. const mkp = (d) => {
  661. const el = document.createElementNS('http://www.w3.org/2000/svg', 'path')
  662. el.setAttribute('d', d)
  663. el.setAttribute('transform', `translate(${-half},${-half}) scale(${scale})`)
  664. el.setAttribute('fill', 'none')
  665. el.setAttribute('stroke', 'currentColor')
  666. el.setAttribute('stroke-width', '1.75')
  667. el.setAttribute('stroke-linecap', 'round')
  668. el.setAttribute('stroke-linejoin', 'round')
  669. parent.appendChild(el)
  670. return el
  671. }
  672. const map = {
  673. ordenador: 'M3 4h18v12H3z M8 16v4 M16 16v4 M6 20h12',
  674. portatil: 'M4 5h16v10H4z M2 17h20v2H2z',
  675. 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',
  676. 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',
  677. tv: 'M2 7h20v12H2z M8 3l4 4 4-4',
  678. 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',
  679. 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',
  680. 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',
  681. 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',
  682. 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',
  683. switch: 'M4 10h16v8H4z M8 10V6 M16 10V6',
  684. 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',
  685. }
  686. mkp(map[type] || map.desconocido)
  687. }
  688. /* ===== render SVG fiel ===== */
  689. function drawTopology() {
  690. const model = buildTopologyModel({
  691. routers: DEMO_ROUTERS, devices: DEMO_DEVICES, wan: DEMO_WAN,
  692. wireguard: DEMO_WG, distributionNodes: DEMO_DISTRIBUTION,
  693. })
  694. const svg = document.getElementById('topoSvg')
  695. svg.innerHTML = ''
  696. const ns = 'http://www.w3.org/2000/svg'
  697. const mk = (tag, attrs = {}, parent = svg) => {
  698. const el = document.createElementNS(ns, tag)
  699. for (const [k, v] of Object.entries(attrs)) if (v !== undefined && v !== null) el.setAttribute(k, v)
  700. if (parent) parent.appendChild(el)
  701. return el
  702. }
  703. // Lección de la app (bug chips invisibles): nunca atributo transform y
  704. // animación CSS de scale en el mismo <g> — el transform CSS machaca el
  705. // translate del atributo y los nodos colapsan en (0,0). El translate va en
  706. // el <g> padre y la animación (opacity/scale con transform-box) en un hijo.
  707. const nodeGroup = (x, y) => {
  708. const outer = mk('g', { transform: `translate(${x} ${y})` })
  709. return mk('g', { class: 'topo-node on' }, outer)
  710. }
  711. // defs
  712. const defs = mk('defs')
  713. const grad = mk('linearGradient', { id: 'topo-gw-grad', x1: 0, y1: 0, x2: 1, y2: 1 }, defs)
  714. mk('stop', { offset: '0%', 'stop-color': TOPO_COLOR.accent, 'stop-opacity': 0.28 }, grad)
  715. mk('stop', { offset: '100%', 'stop-color': TOPO_COLOR.tunnel, 'stop-opacity': 0.28 }, grad)
  716. // anillos guia wifi
  717. const guidesG = mk('g', { 'class': 'topo-guides', 'aria-hidden': 'true' })
  718. for (const node of model.routerNodes) {
  719. const radii = model.ringRadii.get(node.id) || (node.id === model.gatewayNode?.id ? [96, 130] : [82, 120])
  720. for (const r of radii) mk('circle', { cx: node.x, cy: node.y, r, class: 'topo-guide' }, guidesG)
  721. }
  722. // enlaces
  723. const linksG = mk('g')
  724. for (const link of model.links) {
  725. const isWg = link.kind === 'wg'
  726. const isWifiUp = link.kind === 'uplink' && link.wifi
  727. const stroke = linkColor(link.kind, link.wifi)
  728. const baseOpacity = link.kind === 'wired' ? 0.45 : link.kind === 'dist' ? 0.55 : isWifiUp ? 0.8 : link.kind === 'uplink' ? 0.55 : 0.9
  729. const path = mk('path', { d: link.d, fill: 'none', stroke, 'stroke-width': link.width, 'stroke-linecap': 'round',
  730. 'stroke-dasharray': isWg ? '7 7' : isWifiUp ? '8 6' : undefined, opacity: baseOpacity,
  731. id: `topo-link-${link.id}`, class: 'topo-edge on' }, linksG)
  732. if (isWg) {
  733. mk('path', { d: link.d, fill: 'none', stroke: TOPO_COLOR.tunnel, 'stroke-width': link.width, 'stroke-linecap': 'round',
  734. 'stroke-dasharray': '7 7', opacity: 0.9, class: 'topo-wg-flow' }, linksG)
  735. }
  736. // paquetes animados via CSS offset-path
  737. if (link.packets > 0) {
  738. for (let i = 0; i < link.packets; i++) {
  739. const begin = -((link.packetDur / link.packets) * i)
  740. mk('circle', {
  741. r: 2.6, fill: stroke, opacity: 0.95, class: 'topo-packet',
  742. style: `offset-path: path('${link.d.replace(/'/g, "\\'")}'); animation: packetMove ${link.packetDur}s linear infinite; animation-delay: ${begin}s`,
  743. }, linksG)
  744. }
  745. }
  746. }
  747. // internet
  748. const inetG = nodeGroup(model.internetNode.x, model.internetNode.y)
  749. mk('circle', { r: 42, fill: TOPO_COLOR.ok, opacity: 0.08 }, inetG)
  750. const orbit = mk('g', { 'aria-hidden': 'true', class: 'topo-orbit' }, inetG)
  751. mk('circle', { r: 38, fill: 'none', stroke: TOPO_COLOR.ok, 'stroke-width': 1.2, 'stroke-dasharray': '3 7', opacity: 0.55 }, orbit)
  752. mk('circle', { r: 3, fill: TOPO_COLOR.ok, cx: 0, cy: -38 }, orbit)
  753. mk('circle', { r: 28, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.ok, 'stroke-width': 2 }, inetG)
  754. 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',
  755. fill: 'none', stroke: TOPO_COLOR.ok, 'stroke-width': 1.75, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, inetG)
  756. // routers
  757. model.routerNodes.forEach((node, i) => {
  758. const isGw = node.router.roleBadge === 'Principal'
  759. const isWarn = node.router.status === 'warn'
  760. const g = nodeGroup(node.x, node.y)
  761. if (isGw) mk('circle', { r: node.r + 18, fill: TOPO_COLOR.accent, opacity: 0.1, class: 'topo-halo' }, g)
  762. if (isWarn) {
  763. mk('circle', { r: node.r + 8, fill: 'none', stroke: TOPO_COLOR.warn, 'stroke-width': 2, class: 'topo-warn-pulse' }, g)
  764. }
  765. mk('circle', { r: node.r, fill: isGw ? 'url(#topo-gw-grad)' : 'rgb(var(--elevated))',
  766. stroke: isWarn ? TOPO_COLOR.warn : isGw ? TOPO_COLOR.accent : 'rgb(var(--border-strong))', 'stroke-width': isGw || isWarn ? 2 : 1.5 }, g)
  767. // status ring
  768. const R = node.r + 6, C = 2 * Math.PI * R
  769. const target = C * (1 - node.router.health / 100)
  770. const ring = mk('circle', { r: R, fill: 'none', stroke: statusColor(node.router.status), 'stroke-width': 3,
  771. 'stroke-dasharray': C, 'stroke-dashoffset': target, 'stroke-linecap': 'round', transform: 'rotate(-90)' }, g)
  772. // router icon
  773. mk('path', { d: 'M4 10h16v8H4z M8 10V6 M16 10V6 M12 2v4', fill: 'none', stroke: isWarn ? TOPO_COLOR.warn : TOPO_COLOR.accent,
  774. 'stroke-width': 1.75, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, g)
  775. })
  776. // peers
  777. model.peerNodes.forEach((node, i) => {
  778. const isMovil = node.peer.type === 'movil'
  779. const g = nodeGroup(node.x, node.y)
  780. const pulse = mk('circle', { r: 22, fill: 'none', stroke: TOPO_COLOR.tunnel, 'stroke-width': 1.5, class: 'topo-peer-pulse' }, g)
  781. 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)
  782. const path = isMovil
  783. ? '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'
  784. : 'M4 5h16v10H4z M2 17h20v2H2z'
  785. mk('path', { d: path, fill: 'none', stroke: TOPO_COLOR.tunnel, 'stroke-width': 1.75, 'stroke-linecap': 'round', 'stroke-linejoin': 'round' }, g)
  786. })
  787. // hidden peers +N
  788. if (model.hiddenPeers.length > 0) {
  789. const g = nodeGroup(PEERS_OVERFLOW_COORD.x, PEERS_OVERFLOW_COORD.y)
  790. 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)
  791. 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
  792. }
  793. // distnodes
  794. model.distNodes.forEach((dv) => {
  795. const managed = dv.node.kind === 'managed'
  796. const g = nodeGroup(dv.x, dv.y)
  797. mk('circle', { r: dv.r + 5, fill: 'none', stroke: managed ? TOPO_COLOR.accent : 'rgb(var(--text-muted))', 'stroke-width': 1,
  798. 'stroke-dasharray': managed ? undefined : '2 5', opacity: managed ? 0.5 : 0.6 }, g)
  799. mk('circle', { r: dv.r, fill: managed ? 'rgb(var(--elevated))' : 'rgb(var(--elevated) / 0.65)',
  800. stroke: managed ? TOPO_COLOR.accent : 'rgb(var(--text-muted))', 'stroke-width': 1.5, 'stroke-dasharray': managed ? undefined : '4 4' }, g)
  801. 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)
  802. if (managed) {
  803. 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)
  804. 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'
  805. }
  806. })
  807. // chips
  808. model.chips.forEach((chip) => {
  809. const d = chip.device, S = chip.size, half = S / 2
  810. const stroke = d.lldp ? TOPO_COLOR.accent : chip.wired ? TOPO_COLOR.ok : 'rgb(var(--border-strong))'
  811. const g = nodeGroup(chip.x, chip.y)
  812. 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)
  813. const iconG = mk('g', { style: `color: ${chip.wired ? TOPO_COLOR.ok : 'rgb(var(--text-primary))'}` }, g)
  814. drawIcon(d.type, 14, iconG)
  815. if (!chip.wired) {
  816. 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)
  817. }
  818. if (d.lldp) {
  819. 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)
  820. 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'
  821. }
  822. const ctCount = model.ctCountByHost.get(chip.id) || 0
  823. if (ctCount > 0) {
  824. mk('circle', { cx: half + 1, cy: -half - 1, r: 8, fill: 'rgb(var(--elevated))', stroke: TOPO_COLOR.ok, 'stroke-width': 1.2 }, g)
  825. mk('text', { x: half + 1, y: -half + 2, 'text-anchor': 'middle', 'font-size': 8, 'font-weight': 700, fill: TOPO_COLOR.ok }, g).textContent = '+' + ctCount
  826. }
  827. mk('title', {}, g).textContent = tName(d.name)
  828. })
  829. // etiquetas
  830. const labelsG = mk('g', { class: 'topo-labels', 'pointer-events': 'none', 'aria-hidden': 'true' })
  831. function label(x, y, anchor, title, sub, subColor) {
  832. const g = mk('g', {}, labelsG)
  833. 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
  834. 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
  835. }
  836. const linkLabelText = (l) => {
  837. if (l.kind === 'wan') return t('topo.fiber').replace('{plan}', model.wan.plan).replace('{latency}', model.wan.latencyMs)
  838. if (l.kind === 'uplink') return l.wifi ? t('topo.wifiUplink') : t('topo.cable1g') + (l.label.includes('LLDP') ? ' · LLDP' : '')
  839. return ''
  840. }
  841. label(548, 54, 'start', `${t('topo.inet')} · ${model.wan.isp}`, `${model.wan.plan} · ${model.wan.latencyMs} ms`)
  842. if (model.gatewayNode) {
  843. const n = model.gatewayNode
  844. 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')}`)
  845. }
  846. model.apNodes.forEach((n) => {
  847. const warn = n.router.status === 'warn'
  848. 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)
  849. })
  850. model.distNodes.forEach((dv) => {
  851. if (dv.node.kind === 'managed') 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)
  852. else label(dv.x, dv.y - 34, 'middle', t('topo.inferredSwitch'), `${dv.node.port}`)
  853. })
  854. for (const [hostId] of model.ctsByHost) {
  855. const host = model.chips.find((c) => c.id === hostId); if (!host) continue
  856. label(host.x, host.y - 38, 'middle', tName(host.device.name), `${t('topo.hypervisor')} · ${model.ctCountByHost.get(hostId) || 0} CT`)
  857. }
  858. 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))
  859. model.links.filter((l) => l.label).forEach((l) => {
  860. 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)
  861. })
  862. }
  863. function buildTopo() {
  864. if (topoBuilt) return
  865. topoBuilt = true
  866. drawTopology()
  867. }
  868. function renderTopoNames() {
  869. if (topoBuilt) drawTopology()
  870. }
  871. function buildRouters() {
  872. const grid = document.getElementById('routerGrid')
  873. const C = 2 * Math.PI * 25 // r=25 para que el anillo (stroke 5) quepa en el viewBox 56x56 y no se recorte
  874. grid.innerHTML = DEMO_ROUTERS.map(r => {
  875. const isWarn = r.status === 'warn'
  876. const statusColor = isWarn ? 'rgb(var(--warn))' : 'rgb(var(--ok))'
  877. const healthDash = C * (1 - r.health / 100)
  878. const sparkPath = r.sparkline.map((v, i) => `${i === 0 ? 'M' : 'L'}${(i / (r.sparkline.length - 1)) * 100} ${28 - (v / 70) * 28}`).join(' ')
  879. return `
  880. <div class="rcard card ${isWarn ? 'warn' : ''}">
  881. <div class="rt">
  882. <div class="nameblock">
  883. <div class="iconbox">
  884. <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>
  885. </div>
  886. <div>
  887. <span class="name">${tName(r.name)}</span>
  888. <span class="model">${r.model}</span>
  889. <span class="rolepill">${t(r.roleBadge === 'Principal' ? 'routers.roleGW' : 'routers.roleAP')}</span>
  890. </div>
  891. </div>
  892. <div class="ring-wrap" style="width:56px;height:56px;">
  893. <svg width="56" height="56" viewBox="0 0 56 56" style="transform:rotate(-90deg);">
  894. <circle cx="28" cy="28" r="25" fill="none" stroke="rgb(var(--border))" stroke-width="5"/>
  895. <circle class="router-health-ring" cx="28" cy="28" r="25" fill="none" stroke="${statusColor}" stroke-width="5" stroke-linecap="round"
  896. stroke-dasharray="${C}" stroke-dashoffset="${C}" data-target="${healthDash}"/>
  897. </svg>
  898. <div class="ring-center" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;">
  899. <span class="font-mono" style="font-size:0.78rem;font-weight:700;">${r.health}</span>
  900. </div>
  901. </div>
  902. </div>
  903. <div class="minimetrics">
  904. <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>
  905. <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>
  906. <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>
  907. <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>
  908. </div>
  909. <div class="bottom">
  910. <svg class="spark" viewBox="0 0 100 28" preserveAspectRatio="none"><path d="${sparkPath}" vector-effect="non-scaling-stroke"/></svg>
  911. <span class="font-mono" style="font-size:0.75rem;color:rgb(var(--text-muted));">${r.uptime}</span>
  912. <span class="statuspill ${r.status}"><span class="dot"></span>${t(r.status === 'ok' ? 'routers.online' : 'routers.warn')}</span>
  913. <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>
  914. </div>
  915. </div>
  916. `
  917. }).join('')
  918. routersBuilt = true
  919. }
  920. function fillRouterBars(instant) {
  921. const grid = document.getElementById('routerGrid')
  922. grid.querySelectorAll('.router-health-ring').forEach(ring => {
  923. const target = ring.dataset.target
  924. if (instant || reduceMotion) ring.style.strokeDashoffset = target
  925. else setTimeout(() => ring.style.strokeDashoffset = target, 80)
  926. })
  927. }
  928. function renderRouterNames() {
  929. if (!routersBuilt) return
  930. buildRouters()
  931. if (routersPlayed) fillRouterBars(true)
  932. }
  933. function playRouters() {
  934. buildRouters()
  935. routersBuilt = true
  936. if (routersPlayed) { fillRouterBars(true); return }
  937. routersPlayed = true
  938. fillRouterBars(false)
  939. }
  940. /* ---------- stage 4: adguard ---------- */
  941. const AG_DOMAINS = [
  942. { d: 'graph.facebook.com', n: 12840 },
  943. { d: 'ads.doubleclick.net', n: 9315 },
  944. { d: 'app-measurement.com', n: 7602 },
  945. { d: 'telemetry.microsoft.com', n: 4188 },
  946. { d: 'tracking.miui.com', n: 2941 },
  947. ]
  948. let agPlayed = false
  949. function playAdGuard() {
  950. if (agPlayed) return
  951. agPlayed = true
  952. const q = document.getElementById('agQueries')
  953. const b = document.getElementById('agBlocked')
  954. const c = document.getElementById('agClients')
  955. animateNumber(q, 184523, { duration: 1400, format: x => fmtLocale(Math.round(x)) })
  956. animateNumber(b, 23, { duration: 1400, format: x => Math.round(x) + '%' })
  957. animateNumber(c, DEMO.clients, { duration: 1200, format: x => Math.round(x) + '/' + DEMO.clientsTotal })
  958. const bars = document.getElementById('agBars')
  959. if (!bars.childElementCount) {
  960. const max = AG_DOMAINS[0].n
  961. bars.innerHTML = AG_DOMAINS.map(x => `
  962. <div class="ag-bar-row">
  963. <span class="d">${x.d}</span>
  964. <div class="bar"><i data-w="${Math.round((x.n / max) * 100)}"></i></div>
  965. <span class="n">${fmtLocale(x.n)}</span>
  966. </div>
  967. `).join('')
  968. }
  969. bars.querySelectorAll('.bar i').forEach((bar, i) => {
  970. const w = bar.dataset.w
  971. if (reduceMotion) { bar.style.width = w + '%'; return }
  972. setTimeout(() => { bar.style.width = w + '%' }, 150 + i * 120)
  973. })
  974. }
  975. /* ---------- stage 5: alerts ---------- */
  976. const ALERT_ICONS = {
  977. 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>',
  978. 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>',
  979. 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>',
  980. 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>',
  981. }
  982. function renderAlerts() {
  983. const feed = document.getElementById('alertFeed')
  984. if (!feed) return
  985. const items = [
  986. { tone: 'warn', text: t('alerts.a1'), sub: `2 min ${t('alerts.ago')}` },
  987. { tone: 'accent', text: t('alerts.a2'), sub: `11 min ${t('alerts.ago')}` },
  988. { tone: 'info', text: t('alerts.a3'), sub: `1 h ${t('alerts.ago')}` },
  989. { tone: 'ok', text: t('alerts.a4'), sub: `2 h ${t('alerts.ago')}` },
  990. ]
  991. feed.innerHTML = items.map(a => `
  992. <div class="alert-item ${a.tone}">
  993. <span class="ico">${ALERT_ICONS[a.tone]}</span>
  994. <span><span class="t">${a.text}</span><span class="s" style="display:block;">${a.sub}</span></span>
  995. </div>
  996. `).join('')
  997. if (alertsPlayed) feed.querySelectorAll('.alert-item').forEach(el => el.classList.add('on'))
  998. }
  999. let alertsPlayed = false
  1000. function playAlerts() {
  1001. renderAlerts()
  1002. if (alertsPlayed) return
  1003. alertsPlayed = true
  1004. document.querySelectorAll('#alertFeed .alert-item').forEach((el, i) => {
  1005. if (reduceMotion) { el.classList.add('on'); return }
  1006. setTimeout(() => el.classList.add('on'), 150 + i * 260)
  1007. })
  1008. }
  1009. /* ---------- teatro: control de stages por scroll ---------- */
  1010. const STAGE_PLAYERS = [playRing, playTraffic, buildTopo, playRouters, playAdGuard, playAlerts]
  1011. let currentStage = -1
  1012. function setStage(i) {
  1013. if (i === currentStage) return
  1014. currentStage = i
  1015. document.querySelectorAll('.stage').forEach((s, idx) => s.classList.toggle('active', idx === i))
  1016. document.querySelectorAll('.tstep').forEach(s => {
  1017. s.style.opacity = parseInt(s.dataset.stage, 10) === i ? '1' : ''
  1018. })
  1019. STAGE_PLAYERS[i]()
  1020. }
  1021. function initTheater() {
  1022. const steps = [...document.querySelectorAll('.tstep')]
  1023. if (!('IntersectionObserver' in window)) { setStage(0); return }
  1024. const io = new IntersectionObserver(entries => {
  1025. entries.forEach(en => { if (en.isIntersecting) setStage(parseInt(en.target.dataset.stage, 10)) })
  1026. }, { rootMargin: '-42% 0px -42% 0px', threshold: 0 })
  1027. steps.forEach(s => io.observe(s))
  1028. setStage(0)
  1029. }
  1030. /* ---------- reveals on scroll ---------- */
  1031. function initReveals() {
  1032. const els = document.querySelectorAll('.reveal')
  1033. if (reduceMotion || !('IntersectionObserver' in window)) { els.forEach(e => e.classList.add('in')); return }
  1034. const io = new IntersectionObserver(entries => {
  1035. entries.forEach(en => { if (en.isIntersecting) { en.target.classList.add('in'); io.unobserve(en.target) } })
  1036. }, { threshold: 0.12 })
  1037. els.forEach(e => io.observe(e))
  1038. }
  1039. /* ---------- widget apariencia ---------- */
  1040. const MODE_KEY = 'netpulse-web-theme-mode'
  1041. const ACCENT_KEY = 'netpulse-web-accent'
  1042. let themeMode = 'dark'
  1043. let accentId = 'cyan'
  1044. function readStore(k) { try { return localStorage.getItem(k) } catch { return null } }
  1045. function writeStore(k, v) { try { localStorage.setItem(k, v) } catch { /* privado */ } }
  1046. function applyTheme() {
  1047. const root = document.documentElement
  1048. let light = false
  1049. if (themeMode === 'light') light = true
  1050. else if (themeMode === 'system') light = window.matchMedia('(prefers-color-scheme: light)').matches
  1051. root.classList.toggle('light', light)
  1052. const meta = document.querySelector('meta[name="theme-color"]')
  1053. if (meta) meta.content = light ? '#F3F5F9' : '#070B12'
  1054. }
  1055. function applyAccent() { document.documentElement.dataset.accent = accentId }
  1056. function updateAppearancePanel() {
  1057. document.querySelectorAll('#themeSeg button').forEach(b => b.classList.toggle('on', b.dataset.mode === themeMode))
  1058. document.querySelectorAll('#accentSwatches .swatch').forEach(b => b.classList.toggle('on', b.dataset.accent === accentId))
  1059. }
  1060. function setMode(m) {
  1061. themeMode = m; writeStore(MODE_KEY, m); applyTheme(); updateAppearancePanel()
  1062. }
  1063. function setAccent(a) {
  1064. accentId = a; writeStore(ACCENT_KEY, a); applyAccent(); updateAppearancePanel()
  1065. }
  1066. window.setMode = setMode; window.setAccent = setAccent
  1067. function initAppearance() {
  1068. themeMode = readStore(MODE_KEY) || 'dark'
  1069. accentId = readStore(ACCENT_KEY) || 'cyan'
  1070. applyTheme(); applyAccent(); updateAppearancePanel()
  1071. const fab = document.getElementById('appFab')
  1072. const panel = document.getElementById('appPanel')
  1073. fab.addEventListener('click', () => { panel.classList.toggle('open'); fab.setAttribute('aria-expanded', panel.classList.contains('open')) })
  1074. document.addEventListener('click', e => { if (!panel.contains(e.target) && !fab.contains(e.target)) panel.classList.remove('open') })
  1075. document.addEventListener('keydown', e => { if (e.key === 'Escape') panel.classList.remove('open') })
  1076. document.querySelectorAll('#themeSeg button').forEach(b => b.addEventListener('click', () => setMode(b.dataset.mode)))
  1077. document.querySelectorAll('#accentSwatches .swatch').forEach(b => b.addEventListener('click', () => setAccent(b.dataset.accent)))
  1078. window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => { if (themeMode === 'system') applyTheme() })
  1079. }
  1080. /* ---------- copiar comando ---------- */
  1081. function initCopy() {
  1082. const btn = document.getElementById('copyBtn')
  1083. if (!btn) return
  1084. btn.addEventListener('click', async () => {
  1085. const cmd = document.getElementById('installCmd').textContent
  1086. try { await navigator.clipboard.writeText(cmd) } catch {
  1087. const ta = document.createElement('textarea'); ta.value = cmd; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); ta.remove()
  1088. }
  1089. const orig = t('misc.copy')
  1090. btn.textContent = t('misc.copied')
  1091. setTimeout(() => { btn.textContent = orig }, 1600)
  1092. })
  1093. }
  1094. /* ---------- ko-fi placeholder ---------- */
  1095. function initKofi() {
  1096. const link = document.getElementById('kofiLink')
  1097. // TODO(nacho): URL definitiva de Ko-fi — pendiente de que la cree.
  1098. link.href = 'https://github.com/gnacho/netpulse'
  1099. }
  1100. /* ---------- boot ---------- */
  1101. document.addEventListener('DOMContentLoaded', () => {
  1102. initAppearance()
  1103. initBackgroundCanvas()
  1104. renderTicker()
  1105. renderAlerts()
  1106. initReveals()
  1107. initTheater()
  1108. initCopy()
  1109. initKofi()
  1110. heroCountUps()
  1111. })