-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkknetmap.py
More file actions
1853 lines (1645 loc) · 83.9 KB
/
kknetmap.py
File metadata and controls
1853 lines (1645 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
KKNETMAP (v1.8) — Flask + D3.js
Por Otávio Augusto @oaugustopro www.oaugusto.pro
O que está incluso:
- Posição de hosts/portas salva; zoom do grafo e da timeline salvos.
- Sidebar com notas (maior, 90% transparente), edição de cor do elemento e da borda.
- Emojis fixados por host (com busca por nome).
- Eventos (nome, tag, emoji, cor, data/hora + nota) por host/porta.
• Regras de data/hora:
- Só HORA → hoje com essa hora.
- Só DATA → data escolhida com 00:00:00.
- DATA + HORA → exatamente o selecionado.
- Vazio → agora.
• Ao clicar na hora na lista, mini editor (date+time).
• Salva e timeline atualiza automático.
- Timeline:
• Eixo com ticks adaptativos (meses/dias/horas/minutos) conforme span + zoom.
• Zoom da timeline persistente; redimensionável por handle superior.
• Eventos não se sobrepõem (lanes); stems verticais SEMPRE atrás e “coladas” no centro do evento.
• Arrastar evento é vertical (x ancorado no tempo); stem acompanha e volta pra âncora suavemente.
• Card do evento exibe “último octeto” ou “octeto:porta”.
• Clicar no evento destaca o nó no grafo (halo).
- Filtros do grafo (painel minimizável, persistente):
• Allow/Deny por emojis fixados (chips com busca por nome).
• Allow/Deny por REGEX (chips).
• Allow/Deny por NOME (chips) — “nome” = host (nome/IP) ou porta (número/serviço).
• Regras:
- Se HOST casa (nome/regex): host e TODAS as portas ficam visíveis (salvas as outras regras).
- Se PORTA casa: só aquela porta aparece, desde que o host esteja visível.
- Deny em host derruba host + portas; deny em porta derruba só a porta.
- Custom links (duplo clique inicia; Esc cancela):
• Estilos: reta/curva/tracejada, cor, rótulo no centro, notas; conectados centro a centro.
- Marca “KKNETMAP by kktools” no topo, mudando cor e fonte a cada 5min.
- Painel de instruções em Markdown (canto inferior esquerdo), com preview.
- Comentários inline explicando as partes mais importantes.
"""
import os
import json
import re
from datetime import datetime
from flask import Flask, render_template_string, jsonify, request
# =============================================================================
# Config
# =============================================================================
SCAN_FILE = 'hosts.txt'
DATA_FILE = 'data.txt'
# Cores padrão por porta conhecida (mantido)
DEFAULT_PORT_COLORS = {
80: '#E52D2D', 23: '#2D63E5', 443: '#99E52D', 21: '#E52DCE',
25: '#5B2DE5', 110: '#35E52D', 139: '#E52D6B', 445: '#2DA0E5',
143: '#D6E52D', 53: '#BE2DE5', 135: '#2DE589', 8080: '#E5532D',
1723: '#2D3DE5', 3306: '#E5D52D', 111: '#2D80E5', 995: '#E52D80',
993: '#2DE58E', 5900: '#E5A02D', 514: '#4A2DE5', 137: '#E52D47',
138: '#2DD2E5', 548: '#CBC02D', 465: '#AD2DE5', 587: '#2DE595',
631: '#E5C02D', 1025: '#2DCDE5', 2049: '#D52DE5', 6667: '#2DE5A4',
123: '#E52DA9', 179: '#2DE5B3', 636: '#E52DA0', 1900: '#2DE5C1',
69: '#E5922D', 3128: '#2D43E5', 119: '#8AE52D', 1433: '#E52DC0',
554: '#2DE5D5', 512: '#E59F2D', 513: '#6A2DE5', 10000:'#2DE534',
8443: '#E52D5C', 20: '#2D92E5', 161: '#C7E52D', 162: '#CD2DE5',
8000: '#2DE597', 5432: '#E5622D', 1521: '#2D2FE5', 5060: '#64E52D',
5985: '#FF0000', 3389: '#FFD580', 5040: '#FF8C00', 22: '#FFFFFF',
}
# Catálogo de emojis para busca por nome (para pins e para eventos)
EMOJI_CATALOG = [
{"name": "server", "emoji": "🖥️"}, {"name": "database", "emoji": "🗄️"},
{"name": "warning", "emoji": "⚠️"}, {"name": "fire", "emoji": "🔥"},
{"name": "check", "emoji": "✅"}, {"name": "bug", "emoji": "🐞"},
{"name": "lock", "emoji": "🔒"}, {"name": "unlock", "emoji": "🔓"},
{"name": "key", "emoji": "🔑"}, {"name": "lightning", "emoji": "⚡"},
{"name": "satellite", "emoji": "🛰️"},{"name": "globe", "emoji": "🌐"},
{"name": "gear", "emoji": "⚙️"}, {"name": "robot", "emoji": "🤖"},
{"name": "skull", "emoji": "💀"}, {"name": "rocket", "emoji": "🚀"},
{"name": "shield", "emoji": "🛡️"}, {"name": "clock", "emoji": "🕒"},
{"name": "antenna", "emoji": "📡"}, {"name": "folder", "emoji": "📁"},
{"name": "note", "emoji": "📝"}, {"name": "bell", "emoji": "🔔"},
{"name": "plug", "emoji": "🔌"}, {"name": "wifi", "emoji": "📶"},
{"name": "camera", "emoji": "📷"}, {"name": "chip", "emoji": "🧠"},
]
app = Flask(__name__)
# =============================================================================
# Parse + Persist
# =============================================================================
def parse_scan():
"""Lê hosts.txt (saída 'greppable' do nmap) e gera estrutura básica de hosts/portas."""
hosts = []
if not os.path.isfile(SCAN_FILE):
return hosts
with open(SCAN_FILE, encoding='utf-8') as f:
for line in f:
s = line.strip()
if not s or not s.startswith('Host:'):
continue
parts = s.split('\t')
host_part = parts[0][len('Host:'):].strip()
m = re.match(r'([\d\.]+)\s*\((.*?)\)', host_part)
if m:
ip = m.group(1)
name = m.group(2) or ip
else:
ip = host_part.split()[0]
name = ip
ports = []
if len(parts) > 1 and parts[1].startswith('Ports:'):
entries = parts[1][len('Ports:'):].split(',')
for entry in entries:
entry = entry.strip()
if not entry:
continue
tokens = entry.split('/')
try:
pnum = int(tokens[0])
except Exception:
continue
service = tokens[4] if len(tokens) > 4 else ''
ports.append({
'port': pnum,
'service': service,
'note': '',
'border': False,
'border_color': '#FFD400',
'color': None,
'fx': None, 'fy': None,
'events': [],
})
hosts.append({
'id': ip, 'ip': ip, 'name': name,
'note': '',
'border': False,
'border_color': '#FFD400',
'color': None,
'fx': None, 'fy': None,
'pinned_emojis': [],
'events': [],
'ports': ports
})
return hosts
def merge_saved_into_scan(scan_hosts, saved):
"""Mescla estado salvo (data.txt) com resultado atual do scan, preservando posições/notas/cores/eventos etc."""
saved_hosts = saved.get('hosts', {})
for h in scan_hosts:
sid = h['id']
sh = saved_hosts.get(sid, {})
h['note'] = sh.get('note', '')
h['border'] = sh.get('border', False)
h['border_color'] = sh.get('border_color', h.get('border_color', '#FFD400'))
h['color'] = sh.get('color', None)
h['fx'] = sh.get('fx', None)
h['fy'] = sh.get('fy', None)
h['pinned_emojis'] = sh.get('pinned_emojis', [])
h['events'] = sh.get('events', [])
saved_ports = sh.get('ports', {})
for p in h['ports']:
sp = saved_ports.get(str(p['port']), {})
p['note'] = sp.get('note', '')
p['border'] = sp.get('border', False)
p['border_color'] = sp.get('border_color', p.get('border_color', '#FFD400'))
p['color'] = sp.get('color', None)
p['fx'] = sp.get('fx', None)
p['fy'] = sp.get('fy', None)
p['events'] = sp.get('events', [])
return scan_hosts
def load_data():
"""Carrega estado persistido (ou cria defaults)."""
data = {
'hosts': parse_scan(),
'zoom': {'k': 1, 'x': 0, 'y': 0},
'timeline_zoom': {'k': 1, 'x': 0, 'y': 0},
'links': [],
'instructions': ""
}
if not os.path.isfile(DATA_FILE):
return data
try:
with open(DATA_FILE, encoding='utf-8') as f:
saved = json.load(f)
data['hosts'] = merge_saved_into_scan(data['hosts'], saved)
if isinstance(saved.get('zoom'), dict):
z = saved['zoom']; data['zoom'] = {'k': float(z.get('k', 1)), 'x': float(z.get('x', 0)), 'y': float(z.get('y', 0))}
if isinstance(saved.get('timeline_zoom'), dict):
tz = saved['timeline_zoom']; data['timeline_zoom'] = {'k': float(tz.get('k', 1)), 'x': float(tz.get('x', 0)), 'y': float(tz.get('y', 0))}
if isinstance(saved.get('links'), list):
data['links'] = saved['links']
data['instructions'] = saved.get('instructions', "")
except Exception:
pass
return data
def save_data(received):
"""Salva estado em data.txt (formato compacto)."""
out = {
'hosts': {},
'zoom': {'k': 1, 'x': 0, 'y': 0},
'timeline_zoom': {'k': 1, 'x': 0, 'y': 0},
'links': [],
'instructions': received.get('instructions', "")
}
z = received.get('zoom', {}) or {}
out['zoom'] = {'k': float(z.get('k', 1)), 'x': float(z.get('x', 0)), 'y': float(z.get('y', 0))}
tz = received.get('timeline_zoom', {}) or {}
out['timeline_zoom'] = {'k': float(tz.get('k', 1)), 'x': float(tz.get('x', 0)), 'y': float(tz.get('y', 0))}
for l in received.get('links', []):
out['links'].append({
'id': l.get('id'),
'source': l.get('source'),
'target': l.get('target'),
'style': l.get('style', 'straight'),
'color': l.get('color', '#555555'),
'label': l.get('label', ''),
'note': l.get('note', '')
})
for h in received.get('hosts', []):
hid = h.get('id')
if not hid:
continue
out['hosts'][hid] = {
'note': h.get('note', ''),
'border': bool(h.get('border', False)),
'border_color': h.get('border_color', '#FFD400'),
'color': h.get('color', None),
'fx': h.get('fx', None),
'fy': h.get('fy', None),
'pinned_emojis': h.get('pinned_emojis', []),
'events': h.get('events', []),
'ports': {}
}
for p in h.get('ports', []):
pid = str(p.get('port'))
out['hosts'][hid]['ports'][pid] = {
'note': p.get('note', ''),
'border': bool(p.get('border', False)),
'border_color': p.get('border_color', '#FFD400'),
'color': p.get('color', None),
'fx': p.get('fx', None),
'fy': p.get('fy', None),
'events': p.get('events', []),
}
with open(DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(out, f, ensure_ascii=False, indent=2)
# =============================================================================
# Routes
# =============================================================================
@app.route('/data')
def data_route():
return jsonify(load_data())
@app.route('/save', methods=['POST'])
def save_route():
payload = request.get_json(force=True) or {}
save_data(payload)
return jsonify({'status': 'ok', 'ts': datetime.utcnow().isoformat() + 'Z'})
@app.route('/')
def index_route():
"""Template único (HTML/CSS/JS)."""
HOST_EMOJIS = ['🐱', '🐶', '🦊', '🐼', '🐸', '🐵', '🐤', '🦁', '🐷', '🐯']
html = render_template_string("""
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>KKNETMAP</title>
<style>
:root{
--sidebar-w: 360px;
--timeline-h: 230px; /* altura ajustável via handle */
--panel-bg: rgba(255,255,255,0.90); /* 90% transparente como pedido */
}
*{ box-sizing: border-box; }
body{ margin:0; font-family: Inter, system-ui, Arial, sans-serif; background:#f0f0f3; }
/* Marca grande no topo */
#brandHeader{
position:fixed; top:8px; width:100%; text-align:center;
font-weight:900; font-size:clamp(22px,7vw,90px); opacity:0.12;
pointer-events:none; user-select:none; z-index:0; transition:color 800ms ease, font-family 400ms ease;
text-shadow: 0 2px 12px rgba(0,0,0,.18);
}
#brandHeader small{ font-weight:700; font-size:.42em; opacity:.85; }
#topWrap{ position:relative; height: calc(100vh - var(--timeline-h)); }
#canvas{ width:100%; height:100%; display:block; }
/* Painel de filtros do grafo (com header e minimize) */
#topFilters{
position:absolute; left:10px; top:10px; width:520px; z-index:3;
background: var(--panel-bg); border:1px solid #ccc; border-radius:10px; padding:10px 12px;
box-shadow:0 2px 12px rgba(0,0,0,.2); font-size:12px;
}
#topFilters .header{ display:flex; align-items:center; justify-content:space-between; margin-bottom:6px; }
#topFilters .toggle{ cursor:pointer; border:1px solid #bbb; border-radius:6px; padding:2px 8px; background:#fff; font-size:12px; line-height:1; }
#topFilters.collapsed{ width:auto; padding:6px 8px; }
#topFilters.collapsed .body{ display:none; }
.chipsRow{ display:flex; flex-wrap:wrap; gap:6px; align-items:center; }
.chip{ display:inline-flex; gap:6px; align-items:center; padding:2px 8px; border:1px solid #ccc; border-radius:999px; background:#fff; }
.chip .x{ cursor:pointer; font-weight:bold; }
.emojiSearchWrap{ position:relative; margin-top:6px; }
.emojiResults{ position:absolute; background:#fff; border:1px solid #ccc; border-radius:8px; z-index:5; max-height:140px; overflow:auto; width:100%; }
.emojiResults div{ padding:6px 8px; cursor:pointer; }
.emojiResults div:hover{ background:#f1f1f1; }
#topFilters input[type="text"]{ width:100%; padding:6px 8px; border:1px solid #bbb; border-radius:8px; background:#fff; font-size:12px; }
/* Tooltip do grafo */
#tooltip{
position:absolute; max-width:320px; padding:8px 10px; border:1px solid #ddd; border-radius:8px;
background: var(--panel-bg); box-shadow:0 2px 10px rgba(0,0,0,.2); display:none; pointer-events:none; z-index:5;
font-size:12px;
}
/* Sidebar (detalhes) */
#sidebar{
position:absolute; right:10px; top:10px; width:var(--sidebar-w); background:var(--panel-bg); z-index:3;
border:1px solid #ccc; border-radius:10px; box-shadow:0 2px 12px rgba(0,0,0,.2); padding:12px;
max-height: calc(100% - 20px); overflow-y:auto;
}
#sidebar h2{ margin:0 0 8px; font-size:1.2em; }
#sidebar h3{ margin:14px 0 6px; font-size:1em; }
#sidebar label{ display:block; margin:8px 0 4px; font-size:12px; }
#sidebar textarea{
width:100%; height:150px; padding:8px; border:1px solid #bbb; border-radius:8px; background:rgba(255,255,255,.9);
resize:vertical;
}
#sidebar input, #sidebar select { width:100%; padding:6px 8px; border:1px solid #bbb; border-radius:8px; background:#fff; font-size:12px; }
.btn{ display:inline-block; padding:6px 10px; border:1px solid #999; border-radius:8px; background:#fff; cursor:pointer; font-size:12px; margin-right:6px; }
.btn:hover{ background:#f4f4f4; }
.pill{ display:inline-flex; align-items:center; gap:6px; padding:2px 8px; border:1px solid #ccc; border-radius:999px; background:#fff; margin:2px; font-size:12px; }
.pill .x{ cursor:pointer; font-weight:bold; }
/* Halo (destaque) no grafo ao clicar evento na timeline */
@keyframes pulseHalo{ 0%{ r:0; opacity:.9; } 100%{ r:40; opacity:0; } }
.halo{ fill:none; stroke:#FFD54F; stroke-width:8px; opacity:.9; animation: pulseHalo 900ms ease-out forwards; pointer-events:none; }
/* Timeline wrapper + handle de resize */
#timelineWrap{
position:fixed; left:0; bottom:0; width:100%; height: var(--timeline-h); background:#fff; z-index:2;
border-top:1px solid #ddd; display:grid; grid-template-rows: 8px 52px 1fr; /* 8px = handle */
}
#timelineResizer{
cursor:ns-resize; background:linear-gradient(to bottom, #e9e9e9, #f7f7f7);
border-bottom:1px solid #ddd; position:relative;
}
#timelineResizer:after{
content:''; position:absolute; left:50%; top:50%; transform:translate(-50%,-50%);
width:36px; height:3px; border-radius:3px; background:#bbb;
box-shadow: 0 6px 0 #bbb, 0 -6px 0 #bbb;
opacity:.8;
}
/* Filtros da timeline (parte de baixo) */
#timelineFilters{
display:grid; grid-template-columns: 2fr 1.2fr 1.6fr 1.4fr 1.4fr 100px; gap:8px; padding:8px 12px; align-items:center;
border-bottom:1px solid #eee; background:#fafafa;
}
#timelineFilters input, #timelineFilters select { padding:6px 8px; border:1px solid #bbb; border-radius:8px; background:#fff; font-size:12px; }
#timelineSVG{ width:100%; height:100%; }
.evtNode circle{ cursor:pointer; }
.evtNode text{ font-size:10px; text-anchor:middle; }
.evtStem{ stroke:#555; stroke-width:1.5px; }
.evtSelected{ filter: drop-shadow(0 0 6px rgba(255,165,0,.9)); }
.evtLabel{ font-size:10px; text-anchor:middle; }
.timelineAxis text{ font-size:10px; }
/* Notas (Markdown) — canto inferior esquerdo */
#noteToggle{
position:fixed; left:10px; bottom: var(--timeline-h); transform: translateY(-8px);
width:26px; height:26px; border-radius:6px; border:1px solid #bbb; background:#fff; z-index:4;
box-shadow:0 2px 8px rgba(0,0,0,.2); display:flex; align-items:center; justify-content:center; cursor:pointer;
font-weight:bold;
}
#notePanel{
position:fixed; left:10px; bottom: calc(var(--timeline-h) + 32px);
width:420px; max-height:50vh; overflow:auto; z-index:4; display:none;
background:var(--panel-bg); border:1px solid #ccc; border-radius:10px; padding:10px; box-shadow:0 2px 12px rgba(0,0,0,.25);
}
#notePanel h3{ margin:0 0 8px; }
#notePanel textarea{ width:100%; height:160px; border:1px solid #bbb; border-radius:8px; padding:8px; background:#fff; }
#notePreview{ margin-top:8px; background:#fff; border:1px solid #ddd; border-radius:8px; padding:8px; }
</style>
</head>
<body>
<!-- Marca grande -->
<div id="brandHeader">KKNETMAP <small>by kktools</small></div>
<div id="topWrap">
<!-- Painel de filtros (grafo) -->
<div id="topFilters">
<div class="header">
<h3>Filtros (grafo)</h3>
<button id="topFiltersToggle" class="toggle" title="Minimizar">–</button>
</div>
<div class="body">
<!-- ALLOW emojis -->
<div><strong>Allow emojis fixados</strong></div>
<div id="allowChips" class="chipsRow"></div>
<div class="emojiSearchWrap">
<input id="allowSearch" type="text" placeholder="Digite para buscar (ex: rocket, lock...)" />
<div id="allowResults" class="emojiResults" style="display:none"></div>
</div>
<!-- DENY emojis -->
<div style="margin-top:8px"><strong>Deny emojis fixados</strong></div>
<div id="denyChips" class="chipsRow"></div>
<div class="emojiSearchWrap">
<input id="denySearch" type="text" placeholder="Digite para buscar (ex: skull, bug...)" />
<div id="denyResults" class="emojiResults" style="display:none"></div>
</div>
<!-- REGEX allow/deny (chips) -->
<div style="margin-top:10px"><strong>Regex (allow)</strong></div>
<div id="rxAllowChips" class="chipsRow"></div>
<input id="rxAllowInput" type="text" placeholder="Regex, Enter para adicionar (ex: (scan|backup))" />
<div style="margin-top:10px"><strong>Regex (deny)</strong></div>
<div id="rxDenyChips" class="chipsRow"></div>
<input id="rxDenyInput" type="text" placeholder="Regex, Enter para adicionar (ex: tmp|teste)" />
<!-- NOME allow/deny (chips) -->
<div style="margin-top:10px"><strong>Nome (allow)</strong> <small>(host ou porta; ex: 22, web, db)</small></div>
<div id="nmAllowChips" class="chipsRow"></div>
<input id="nmAllowInput" type="text" placeholder="Termo, Enter para adicionar" />
<div style="margin-top:10px"><strong>Nome (deny)</strong> <small>(host ou porta; ex: lab, dev)</small></div>
<div id="nmDenyChips" class="chipsRow"></div>
<input id="nmDenyInput" type="text" placeholder="Termo, Enter para adicionar" />
</div>
</div>
<!-- Grafo -->
<svg id="canvas"></svg>
<!-- Tooltip -->
<div id="tooltip"></div>
<!-- Sidebar (detalhes) -->
<div id="sidebar">
<h2>Detalhes</h2>
<div id="info">Clique em um host, porta, ou link para editar. Duplo clique em um nó inicia um link; <b>Esc</b> cancela.</div>
</div>
</div>
<!-- Botão/caixa de anotações (Markdown) -->
<div id="noteToggle">✎</div>
<div id="notePanel">
<h3>Instruções do NetMap (Markdown)</h3>
<textarea id="noteInput" placeholder="Escreva aqui suas instruções/legenda de organização. Markdown suportado."></textarea>
<div id="notePreview"></div>
<div style="margin-top:8px"><button id="noteSave" class="btn">Salvar</button> <button id="noteClose" class="btn">Fechar</button></div>
</div>
<!-- Timeline -->
<div id="timelineWrap">
<div id="timelineResizer" title="Arraste para redimensionar a timeline"></div>
<div id="timelineFilters">
<input id="fltText" placeholder="Regex em nome/tag/host (ex: busca|scan)" />
<select id="fltEmoji"><option value="">Emoji</option></select>
<select id="fltHost"><option value="">Todos os hosts</option></select>
<input id="fltFrom" type="date" />
<input id="fltTo" type="date" />
<button id="fltClear" class="btn">Limpar</button>
</div>
<svg id="timelineSVG"></svg>
</div>
<!-- Libs -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
// === Dados vindos do backend ===
const DEFAULT_PORT_COLORS = {{ default_port_colors | tojson }};
const HOST_EMOJIS = {{ host_emojis | tojson }};
const EMOJI_CATALOG = {{ emoji_catalog | tojson }};
// === SVG principal + grupos/layers ===
const svg = d3.select('#canvas');
const gRoot = svg.append('g'); // tudo que sofre zoom/pan
const gBuiltins = gRoot.append('g').attr('id','gBuiltins'); // links host↔porta
const gCustomLinks = gRoot.append('g').attr('id','gCustomLinks'); // links desenhados
const gNodes = gRoot.append('g').attr('id','gNodes'); // nós (hosts/portas)
const gLabels = gRoot.append('g').attr('id','gLabels'); // labels (emoji/número)
const gPins = gRoot.append('g').attr('id','gPins'); // emojis fixados
const gHalo = gRoot.append('g').attr('id','gHalo'); // halos de destaque
const tooltip = d3.select('#tooltip');
const topWrap = document.getElementById('topWrap');
// === Timeline ===
const tlSVG = d3.select('#timelineSVG');
const tlAxisG = tlSVG.append('g').attr('class','timelineAxis');
// stems no fundo (linhas verticais)
const tlStemsG = tlSVG.append('g').attr('class','timelineStems');
// eventos acima
const tlG = tlSVG.append('g');
// === Estado global ===
let state = {
hosts: [],
links: [],
zoom: {k:1,x:0,y:0},
timeline_zoom: {k:1,x:0,y:0},
instructions: ""
};
// === Simulador do grafo ===
let simulation = null;
let simNodes = [], simLinks = [];
let builtInLinksSel = null, nodeSel = null, labelSel = null, pinSel = null;
let customLinkSel = null, customLinkLabelSel = null;
// Seleção atual (para painel de detalhes e highlight na timeline)
let selected = null;
// Largura da borda quando ativada por clique direito
const BORDER_WIDTH = 6;
// ---------------- Util de cor: clarear o fill para destacar bordas/pins ----------------
function lightenColor(c, amt=0.14){
const col = d3.color(c) || d3.color('#9aa');
const hsl = d3.hsl(col);
hsl.l = Math.min(1, hsl.l + amt);
return hsl.formatHex();
}
function colorForHost(host, idx){
const base = host.color || d3.schemeCategory10[idx % 10];
return lightenColor(base, 0.12);
}
function colorForPort(port){
const base = port.color || DEFAULT_PORT_COLORS[port.port] || '#9E9E9E';
return lightenColor(base, 0.10);
}
// ---------------- Persistência ----------------
function saveAll(){
const payload = {
hosts: state.hosts.map(h => ({
id:h.id, ip:h.ip, name:h.name,
note:h.note||'', border:!!h.border, border_color:h.border_color||'#FFD400',
color:h.color||null,
fx: typeof h.fx==='number'?h.fx:null, fy: typeof h.fy==='number'?h.fy:null,
pinned_emojis: Array.isArray(h.pinned_emojis)?h.pinned_emojis:[],
events: Array.isArray(h.events)?h.events:[],
ports: h.ports.map(p => ({
port:p.port, service:p.service,
note:p.note||'', border:!!p.border, border_color:p.border_color||'#FFD400',
color:p.color||null,
fx: typeof p.fx==='number'?p.fx:null, fy: typeof p.fy==='number'?p.fy:null,
events: Array.isArray(p.events)?p.events:[]
}))
})),
links: state.links.map(l => ({
id:l.id, source:l.source, target:l.target,
style:l.style||'straight', color:l.color||'#555555',
label:l.label||'', note:l.note||''
})),
zoom: state.zoom,
timeline_zoom: state.timeline_zoom,
instructions: state.instructions || ""
};
fetch('/save',{method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(payload)}).catch(()=>{});
}
// IDs helper
function newId(prefix='id'){ return prefix + '-' + Date.now().toString(36) + Math.random().toString(36).slice(2,7); }
function findHost(id){ return state.hosts.find(h => h.id === id) || null; }
function findPort(hostId, port){ const h=findHost(hostId); return h ? (h.ports.find(p=>p.port===port)||null) : null; }
function pid(hostId, port){ return hostId + '_' + port; }
// ---------------- Zoom/Pan do grafo (persistente) ----------------
let currentTransform = d3.zoomIdentity;
const zoomBehavior = d3.zoom()
.scaleExtent([0.2, 5])
.on('zoom', ev => {
currentTransform = ev.transform;
gRoot.attr('transform', currentTransform);
})
.on('end', () => {
state.zoom = { k: currentTransform.k, x: currentTransform.x, y: currentTransform.y };
saveAll();
});
svg.call(zoomBehavior);
function applySavedZoom(z){
currentTransform = d3.zoomIdentity.translate(z.x||0, z.y||0).scale(z.k||1);
svg.call(zoomBehavior.transform, currentTransform);
}
function resizeSVG(){ svg.attr('width', topWrap.clientWidth).attr('height', topWrap.clientHeight); }
window.addEventListener('resize', resizeSVG);
// ---------------- Filtros do grafo: emojis allow/deny ----------------
const allowChips = document.getElementById('allowChips');
const allowSearch = document.getElementById('allowSearch');
const allowResults = document.getElementById('allowResults');
const denyChips = document.getElementById('denyChips');
const denySearch = document.getElementById('denySearch');
const denyResults = document.getElementById('denyResults');
const allowSet = new Set(); // emojis allow
const denySet = new Set(); // emojis deny
function renderChips(container, setRef){
container.innerHTML = '';
Array.from(setRef).forEach(emoji=>{
const el = document.createElement('span');
el.className = 'chip';
el.textContent = emoji + ' ';
const x = document.createElement('span');
x.className = 'x'; x.textContent = '×';
x.onclick = ()=>{ setRef.delete(emoji); renderChips(container, setRef); applyTopFiltersVisibility(); };
el.appendChild(x);
container.appendChild(el);
});
}
function attachEmojiSearch(input, resultsBox, onPick){
input.addEventListener('input', ()=>{
const q = (input.value||'').trim().toLowerCase();
if (!q){ resultsBox.style.display='none'; resultsBox.innerHTML=''; return; }
const hits = EMOJI_CATALOG.filter(e=> e.name.includes(q)).slice(0,12);
resultsBox.innerHTML = '';
hits.forEach(e=>{
const div = document.createElement('div');
div.textContent = `${e.emoji} ${e.name}`;
div.onclick = ()=>{ onPick(e.emoji); input.value=''; resultsBox.style.display='none'; resultsBox.innerHTML=''; };
resultsBox.appendChild(div);
});
resultsBox.style.display = hits.length ? 'block' : 'none';
});
document.addEventListener('click', (ev)=>{
if (!resultsBox.contains(ev.target) && ev.target!==input){ resultsBox.style.display='none'; }
});
}
attachEmojiSearch(allowSearch, allowResults, (emoji)=>{ allowSet.add(emoji); renderChips(allowChips, allowSet); applyTopFiltersVisibility(); });
attachEmojiSearch(denySearch, denyResults, (emoji)=>{ denySet.add(emoji); renderChips(denyChips, denySet); applyTopFiltersVisibility(); });
// ---------------- Regex + Nome (allow/deny) em chips ----------------
const rxAllowChips = document.getElementById('rxAllowChips');
const rxDenyChips = document.getElementById('rxDenyChips');
const rxAllowInput = document.getElementById('rxAllowInput');
const rxDenyInput = document.getElementById('rxDenyInput');
const nmAllowChips = document.getElementById('nmAllowChips');
const nmDenyChips = document.getElementById('nmDenyChips');
const nmAllowInput = document.getElementById('nmAllowInput');
const nmDenyInput = document.getElementById('nmDenyInput');
const rxAllow = new Set();
const rxDeny = new Set();
const nmAllow = new Set();
const nmDeny = new Set();
function renderChipsGeneric(container, setRef){
container.innerHTML='';
Array.from(setRef).forEach(token=>{
const el = document.createElement('span');
el.className = 'chip';
el.textContent = token + ' ';
const x = document.createElement('span');
x.className = 'x'; x.textContent = '×';
x.onclick = ()=>{ setRef.delete(token); renderChipsGeneric(container, setRef); applyTopFiltersVisibility(); };
el.appendChild(x);
container.appendChild(el);
});
}
function onEnter(el, cb){ el.addEventListener('keydown', e=>{ if (e.key==='Enter'){ e.preventDefault(); cb(); }}); }
onEnter(rxAllowInput, ()=>{ const v=(rxAllowInput.value||'').trim(); if(!v) return; rxAllow.add(v); rxAllowInput.value=''; renderChipsGeneric(rxAllowChips,rxAllow); applyTopFiltersVisibility(); });
onEnter(rxDenyInput, ()=>{ const v=(rxDenyInput.value||'').trim(); if(!v) return; rxDeny.add(v); rxDenyInput.value=''; renderChipsGeneric(rxDenyChips,rxDeny); applyTopFiltersVisibility(); });
onEnter(nmAllowInput, ()=>{ const v=(nmAllowInput.value||'').trim(); if(!v) return; nmAllow.add(v.toLowerCase()); nmAllowInput.value=''; renderChipsGeneric(nmAllowChips,nmAllow); applyTopFiltersVisibility(); });
onEnter(nmDenyInput, ()=>{ const v=(nmDenyInput.value||'').trim(); if(!v) return; nmDeny.add(v.toLowerCase()); nmDenyInput.value=''; renderChipsGeneric(nmDenyChips,nmDeny); applyTopFiltersVisibility(); });
function compileRegexSet(setRef){
const arr=[];
setRef.forEach(pat=>{
try{ arr.push(new RegExp(pat,'i')); }catch(e){ /* ignora inválidos */ }
});
return arr;
}
// Texto agregados para busca (lowercase)
function aggregateHostText(h){
let text = (h.name||'')+' '+(h.id||'')+' '+(h.note||'');
h.ports.forEach(p=>{
text += ' ' + (p.service||'') + ' ' + (p.note||'');
(p.events||[]).forEach(ev=>{
text += ' ' + (ev.name||'') + ' ' + (ev.tag||'') + ' ' + (ev.note||'');
});
});
(h.events||[]).forEach(ev=>{
text += ' ' + (ev.name||'') + ' ' + (ev.tag||'') + ' ' + (ev.note||'');
});
state.links.forEach(l=>{
if (l.source===h.id || l.target===h.id){
text += ' ' + (l.label||'') + ' ' + (l.note||'');
}
});
return text.toLowerCase();
}
function aggregatePortText(h, p){
let text = (p.service||'') + ' ' + (p.note||'');
(p.events||[]).forEach(ev=>{
text += ' ' + (ev.name||'') + ' ' + (ev.tag||'') + ' ' + (ev.note||'');
});
return (aggregateHostText(h) + ' ' + text).toLowerCase();
}
function hostNameString(h){ return ((h.name||'')+' '+(h.id||'')).toLowerCase(); }
function portNameString(p){ return ((String(p.port)||'')+' '+(p.service||'')).toLowerCase(); }
// ---------------- Lógica de filtro do grafo ----------------
function visibleByTopFilters(node){
// Emojis (host-level)
function pinsPass(h){
const pins = new Set((h.pinned_emojis||[]));
if (allowSet.size){
let hit=false; allowSet.forEach(e=>{ if(pins.has(e)) hit=true; });
if (!hit) return false;
}
if (denySet.size){
let bad=false; denySet.forEach(e=>{ if(pins.has(e)) bad=true; });
if (bad) return false;
}
return true;
}
const rxAllowArr = compileRegexSet(rxAllow);
const rxDenyArr = compileRegexSet(rxDeny);
const hasAllowAny = rxAllow.size || nmAllow.size;
function matchAnyRegex(arr, text){ for (const r of arr){ if (r.test(text)) return true; } return false; }
function matchAnyTerm(setRef, text){ let ok=false; setRef.forEach(t=>{ if(t && text.includes(t)) ok=true; }); return ok; }
if (node.type==='host'){
const h = findHost(node.id); if (!h) return true;
if (!pinsPass(h)) return false;
const hostAgg = aggregateHostText(h);
const hostName = hostNameString(h);
// deny em host derruba host e portas
if (matchAnyRegex(rxDenyArr, hostAgg) || matchAnyTerm(nmDeny, hostName)) return false;
// allow: host aparece se ele mesmo ou alguma porta casa
if (hasAllowAny){
const hostHit = matchAnyRegex(rxAllowArr, hostAgg) || matchAnyTerm(nmAllow, hostName);
if (hostHit) return true;
for (const p of h.ports){
const pAgg = aggregatePortText(h,p);
const pName = portNameString(p);
const pHit = matchAnyRegex(rxAllowArr, pAgg) || matchAnyTerm(nmAllow, pName);
if (pHit) return true; // host visível se QUALQUER porta bateu allow
}
return false;
}
return true;
}
// Porta:
const h = findHost(node.parent); if (!h) return true;
// Host precisa ser visível pelos critérios de host (sem considerar esta porta específica)
const pinsOk = (function(){
const pins = new Set((h.pinned_emojis||[]));
if (allowSet.size){
let hit=false; allowSet.forEach(e=>{ if(pins.has(e)) hit=true; });
if (!hit) return false;
}
if (denySet.size){
let bad=false; denySet.forEach(e=>{ if(pins.has(e)) bad=true; });
if (bad) return false;
}
return true;
})();
if (!pinsOk) return false;
const hostAgg = aggregateHostText(h);
const hostName = hostNameString(h);
if (matchAnyRegex(rxDenyArr, hostAgg) || matchAnyTerm(nmDeny, hostName)) return false;
const p = findPort(node.parent, node.port) || {};
const pAgg = aggregatePortText(h,p);
const pName = portNameString(p);
// deny em porta derruba só a porta
if (matchAnyRegex(rxDenyArr, pAgg) || matchAnyTerm(nmDeny, pName)) return false;
// allow ativo?
if (hasAllowAny){
const hostAllowHit = matchAnyRegex(rxAllowArr, hostAgg) || matchAnyTerm(nmAllow, hostName);
if (hostAllowHit) return true; // host bateu allow → todas as portas aparecem
const selfHit = matchAnyRegex(rxAllowArr, pAgg) || matchAnyTerm(nmAllow, pName);
return !!selfHit; // senão, só a porta que bate allow
}
return true;
}
function applyTopFiltersVisibility(){
const visibleIds = new Set();
simNodes.forEach(n=>{ if (visibleByTopFilters(n)) visibleIds.add(n.id); });
// Nós/labels/pins
gNodes.selectAll('circle.node').style('display', d=> visibleIds.has(d.id)?null:'none');
gLabels.selectAll('text.nodeLabel').style('display', d=> visibleIds.has(d.id)?null:'none');
gPins.selectAll('g.pinHost').style('display', d=> visibleIds.has(d.id)?null:'none');
// Links (built-in e custom) só se AMBOS lados estiverem visíveis
gBuiltins.selectAll('line.builtinLink').style('display', d=>{
const aId = (typeof d.source==='object')?d.source.id:d.source;
const bId = (typeof d.target==='object')?d.target.id:d.target;
return (visibleIds.has(aId) && visibleIds.has(bId))?null:'none';
});
gCustomLinks.selectAll('path.customLink').style('display', d=> (visibleIds.has(d.source) && visibleIds.has(d.target))?null:'none');
gCustomLinks.selectAll('text.customLinkLabel').style('display', d=> (visibleIds.has(d.source) && visibleIds.has(d.target))?null:'none');
}
// ---------------- Monta dados p/ simulação ----------------
function rebuildSimData(){
simNodes = [];
simLinks = [];
state.hosts.forEach((h,i)=>{
simNodes.push({
id:h.id, type:'host',
label:h.name, ip:h.id,
note:h.note, border:h.border, border_color:h.border_color,
color: colorForHost(h,i), r: 30 + h.ports.length * 2, // leve variação por nº de portas
emoji: (HOST_EMOJIS[i % HOST_EMOJIS.length] || '🐾') + h.ip.split('.').pop(),
fx:h.fx, fy:h.fy,
pinned_emojis: Array.isArray(h.pinned_emojis)?h.pinned_emojis:[]
});
h.ports.forEach(p=>{
const isHttp = /^http/.test(p.service);
simNodes.push({
id: pid(h.id, p.port), type:'port',
port: p.port, service:p.service, parent:h.id,
note:p.note, border:p.border, border_color:p.border_color,
color: isHttp ? lightenColor('#FF9800',0.05) : colorForPort(p), r: 15,
fx:p.fx, fy:p.fy
});
simLinks.push({ source:h.id, target: pid(h.id, p.port), builtIn:true });
});
});
}
// ---------------- Criação de links custom (duplo clique inicia; Esc cancela) ----------------
const draft = { active:false, source:null, temp:null };
function startDraft(sourceNode){
draft.active = true;
draft.source = sourceNode.id;
draft.temp = gCustomLinks.append('path')
.attr('class','draftLink')
.attr('stroke', '#888').attr('stroke-width', 2).attr('fill','none')
.attr('pointer-events','none');
svg.on('mousemove.draft', e=>{
if (!draft.active) return;
const p = d3.pointer(e, gRoot.node());
const src = nodeById(draft.source);
draft.temp.attr('d', `M ${src.x},${src.y} L ${p[0]},${p[1]}`);
});
window.addEventListener('keydown', escCancelDraft);
}
function escCancelDraft(e){ if (e.key === 'Escape'){ stopDraft(); } }
function maybeFinishDraft(targetNode){
if (!draft.active) return false;
if (targetNode.id === draft.source){ stopDraft(); return true; }
const link = { id:newId('link'), source:draft.source, target:targetNode.id, style:'straight', color:'#555555', label:'', note:'' };
state.links.push(link);
stopDraft(); saveAll(); renderGraph(); selectLink(link);
return true;
}
function stopDraft(){
draft.active = false; draft.source = null;
if (draft.temp){ draft.temp.remove(); draft.temp=null; }
svg.on('mousemove.draft', null);
window.removeEventListener('keydown', escCancelDraft);
}
// ---------------- Render do grafo ----------------
function renderGraph(){
rebuildSimData();
// Links host↔porta (built-in)
builtInLinksSel = gBuiltins.selectAll('line.builtinLink').data(simLinks, d => d.source+'->'+d.target);
builtInLinksSel.exit().remove();
builtInLinksSel = builtInLinksSel.enter().append('line')
.attr('class', 'builtinLink').attr('stroke', '#aaa')
.merge(builtInLinksSel);
// Links custom
customLinkSel = gCustomLinks.selectAll('path.customLink').data(state.links, d=>d.id);
customLinkSel.exit().remove();
customLinkSel = customLinkSel.enter().append('path')
.attr('class','customLink').attr('fill','none').attr('stroke-width', 2)
.on('click', (ev,l)=>{ ev.stopPropagation(); selectLink(l); })
.merge(customLinkSel);
customLinkLabelSel = gCustomLinks.selectAll('text.customLinkLabel').data(state.links, d=>d.id);
customLinkLabelSel.exit().remove();
customLinkLabelSel = customLinkLabelSel.enter().append('text')
.attr('class','customLinkLabel').attr('font-size','12px').attr('text-anchor','middle').attr('dy', -6)
.on('click', (ev,l)=>{ ev.stopPropagation(); selectLink(l); })
.merge(customLinkLabelSel);
// Nós
nodeSel = gNodes.selectAll('circle.node').data(simNodes, d => d.id);
nodeSel.exit().remove();
nodeSel = nodeSel.enter().append('circle')
.attr('class','node')
.attr('r', d=>d.r)
.attr('fill', d=>d.color)
.attr('stroke', d=> d.border ? (d.border_color||'#FFD400') : 'none')
.attr('stroke-width', d=> d.border ? BORDER_WIDTH : 0)
.on('dblclick', (ev,d)=> { ev.stopPropagation(); startDraft(d); }) // duplo clique inicia criação de link
.on('click', (ev,d)=> { // clique apenas seleciona
ev.stopPropagation();
if (draft.active){ maybeFinishDraft(d); return; }
selectNode(d);
})
.on('contextmenu', (ev,d)=>{
// botão direito alterna borda e salva
ev.preventDefault();
d.border = !d.border;
d3.select(ev.currentTarget)
.attr('stroke', d.border ? (d.border_color||'#FFD400') : 'none')
.attr('stroke-width', d.border ? BORDER_WIDTH : 0);
if (d.type==='host'){ const h=findHost(d.id); if (h) h.border=d.border; }
else { const p=findPort(d.parent,d.port); if (p) p.border=d.border; }
saveAll();
})
.call(d3.drag().on('start', dragStarted).on('drag', dragged).on('end', dragEnded))
.on('mousemove', (ev,d)=> showTooltip(ev,d))
.on('mouseout', ()=> hideTooltip())
.merge(nodeSel);
// Labels dos nós (emoji do host / número da porta)
labelSel = gLabels.selectAll('text.nodeLabel').data(simNodes, d => 'label-'+d.id);
labelSel.exit().remove();
labelSel = labelSel.enter().append('text')
.attr('class','nodeLabel').attr('dy','.35em').attr('text-anchor','middle')
.attr('font-size', d=> d.type==='host' ? '24px' : '12px')
.text(d=> d.type==='port' ? d.port : d.emoji)
.merge(labelSel);
// Emojis fixados (no topo direito do host)
pinSel = gPins.selectAll('g.pinHost').data(simNodes.filter(n=>n.type==='host'), d=>'pin-'+d.id);
pinSel.exit().remove();
const pinEnter = pinSel.enter().append('g').attr('class','pinHost');
pinEnter.merge(pinSel).each(function(h){
const g = d3.select(this);
const items = g.selectAll('text.pinEmoji').data(h.pinned_emojis || []);
items.exit().remove();
items.enter().append('text').attr('class','pinEmoji').attr('font-size','14px').text(d=>d).merge(items);
});
// Simulador físico (forces)
if (!simulation){
simulation = d3.forceSimulation(simNodes)
.force('link', d3.forceLink(simLinks).id(d=>d.id).distance(100))
.force('collision', d3.forceCollide().radius(d=>d.r+10))
.on('tick', ticked);
} else {
simulation.nodes(simNodes).on('tick', ticked);
simulation.force('link').links(simLinks);