forked from uraninite/israel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOSINTVIEW.js
More file actions
1339 lines (1176 loc) · 49.9 KB
/
OSINTVIEW.js
File metadata and controls
1339 lines (1176 loc) · 49.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
'use strict';
/* ═══════════════════════════════════════════════════════════════
1. CONFIGURATION
═══════════════════════════════════════════════════════════════ */
let MAPBOX_TOKEN = '';
// Check for token from HTML handler and initialize
function initAppWithToken() {
MAPBOX_TOKEN = 'pk.eyJ1IjoiZnJhbmtkaW1pdHJpIiwiYSI6ImNsZ25udHpzazA5c3Ezc3BqYWRvY3pwdTIifQ.hYxDNOe-gRNb-rDjImyusQ';
mapboxgl.accessToken = 'pk.eyJ1IjoiZnJhbmtkaW1pdHJpIiwiYSI6ImNsZ25udHpzazA5c3Ezc3BqYWRvY3pwdTIifQ.hYxDNOe-gRNb-rDjImyusQ';
updateRangeUI();
initMap();
}
// On DOMContentLoaded, check if token was set
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initAppWithToken);
} else {
setTimeout(initAppWithToken, 100);
}
const MAP_STYLES = {
light: 'mapbox://styles/mapbox/light-v11',
satellite: 'mapbox://styles/mapbox/satellite-streets-v12',
dark: 'mapbox://styles/mapbox/dark-v11',
};
// Category definitions — order matters for detection (more specific first)
const CATS = [
{ key: 'nukleer', kws: ['nükleer','nuclear','reaktör','atom','nükleer'], color: '#6A1B9A', label: 'Nükleer' },
{ key: 'hava', kws: ['hava','airport','airbase','havalimanı','hava üs'], color: '#1565C0', label: 'Hava Üssü' },
{ key: 'liman', kws: ['liman','port','deniz','naval','tersane','deniz üs'],color: '#00695C', label: 'Liman/Deniz' },
{ key: 'radar', kws: ['radar','anten','sinyal','iletişim','telekom'], color: '#FF6F00', label: 'Radar/İletişim' },
{ key: 'askeri', kws: ['askeri','military','kışla','komuta','ordu','garnizon','jandarma'], color: '#B71C1C', label: 'Askeri' },
{ key: 'enerji', kws: ['enerji','santral','elektrik','güç','power','baraj'],color: '#F9A825', label: 'Enerji' },
{ key: 'arastirma', kws: ['araştırma','research','üniversite','laboratuvar','lab','tübitak'], color: '#558B2F', label: 'Araştırma' },
{ key: 'depo', kws: ['depo','lojistik','ambar','depolama','ikmal'], color: '#4E342E', label: 'Depo/Lojistik' },
{ key: 'tunel', kws: ['tünel','yeraltı','bunker','sığınak','yeralt'], color: '#212121', label: 'Tünel/Bunker' },
{ key: 'sanayi', kws: ['sanayi','fabrika','factory','endüstri','imalat'], color: '#37474F', label: 'Sanayi' },
{ key: 'unknown', kws: [], color: '#9E9E9E', label: 'Bilinmiyor' },
];
const STATUS_COLORS = {
'AKTİF': '#2E7D32',
'PASİF': '#9E9E9E',
'KONTROL ET': '#E65100',
'KRİTİK': '#B71C1C',
};
const ITEM_H = 78; // Virtual scroll item height
const OVERSCAN = 6;
/* ═══════════════════════════════════════════════════════════════
2. STATE
═══════════════════════════════════════════════════════════════ */
const S = {
raw: [], // All parsed facilities
filtered: [], // Filtered + sorted array (for list)
catCounts: {}, // { catKey: count }
statusSet: new Set(), // All unique statuses in data
activeCats: new Set(CATS.map(c=>c.key)),
activeStatuses: new Set(),
critRange: [0, 100],
search: '',
sortField: 'Kritiklik',
sortDir: -1, // -1 = desc
selectedId: null,
map: null,
mapReady: false,
currentStyle: 'light',
vs: { start: 0, end: 0 }, // Virtual scroll window
};
/* ═══════════════════════════════════════════════════════════════
3. CATEGORY HELPERS
═══════════════════════════════════════════════════════════════ */
function detectCat(kategori) {
if (!kategori) return 'unknown';
const low = kategori.toLowerCase();
for (const c of CATS) {
if (c.key === 'unknown') continue;
if (c.kws.some(kw => low.includes(kw))) return c.key;
}
return 'unknown';
}
function catByKey(key) {
return CATS.find(c => c.key === key) || CATS[CATS.length-1];
}
function critColor(score) {
if (score <= 33) return '#43A047';
if (score <= 66) return '#FB8C00';
return '#E53935';
}
function statusColor(status) {
return STATUS_COLORS[status] || '#546E7A';
}
/* ═══════════════════════════════════════════════════════════════
4. ICON GENERATION — canvas → Mapbox addImage
Each icon: filled circle bg + white symbol
═══════════════════════════════════════════════════════════════ */
const ICON_SIZE = 36;
const ICON_DPR = 2;
const _iconGenCache = {}; // Cache rendered icons to avoid regeneration
const PERF_METRICS = { iconsGenerated: 0, layerRenders: 0 };
function genIcon(catKey, color, size = ICON_SIZE) {
// Cache key for this icon generation
const cacheKey = `${catKey}_${color}_${size}`;
if (_iconGenCache[cacheKey]) return _iconGenCache[cacheKey];
const w = size * ICON_DPR, h = size * ICON_DPR;
const c = document.createElement('canvas');
c.width = w; c.height = h;
const ctx = c.getContext('2d');
ctx.scale(ICON_DPR, ICON_DPR);
const cx = size/2, cy = size/2;
const r = size/2 - 2.5;
// Background circle with subtle drop shadow
ctx.save();
ctx.shadowColor = 'rgba(0,0,0,0.28)';
ctx.shadowBlur = 4;
ctx.shadowOffsetY = 2;
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI*2);
ctx.fillStyle = color;
ctx.fill();
ctx.restore();
// White border ring
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI*2);
ctx.strokeStyle = 'rgba(255,255,255,0.8)';
ctx.lineWidth = 1.5;
ctx.stroke();
// Icon
ctx.fillStyle = 'white';
ctx.strokeStyle = 'white';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
const ir = r * 0.52;
switch (catKey) {
case 'hava': drawIcon_airplane(ctx, cx, cy, ir); break;
case 'nukleer': drawIcon_radiation(ctx, cx, cy, ir); break;
case 'liman': drawIcon_anchor(ctx, cx, cy, ir); break;
case 'radar': drawIcon_radar(ctx, cx, cy, ir); break;
case 'askeri': drawIcon_star(ctx, cx, cy, ir); break;
case 'enerji': drawIcon_lightning(ctx, cx, cy, ir); break;
case 'arastirma': drawIcon_diamond(ctx, cx, cy, ir); break;
case 'depo': drawIcon_box(ctx, cx, cy, ir); break;
case 'tunel': drawIcon_tunnel(ctx, cx, cy, ir); break;
case 'sanayi': drawIcon_gear(ctx, cx, cy, ir); break;
default: drawIcon_unknown(ctx, cx, cy, ir, size); break;
}
const imgData = { data: ctx.getImageData(0, 0, w, h).data, width: w, height: h };
_iconGenCache[cacheKey] = imgData;
PERF_METRICS.iconsGenerated++;
return imgData;
}
function drawIcon_airplane(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy); ctx.rotate(-Math.PI/4);
ctx.beginPath();
ctx.ellipse(0, 0, r*0.28, r, 0, 0, Math.PI*2);
ctx.fill();
ctx.beginPath();
ctx.ellipse(0, -r*0.15, r, r*0.22, 0, 0, Math.PI*2);
ctx.fill();
ctx.beginPath();
ctx.ellipse(0, r*0.65, r*0.5, r*0.14, 0, 0, Math.PI*2);
ctx.fill();
ctx.restore();
}
function drawIcon_radiation(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
for (let i=0; i<3; i++) {
ctx.save(); ctx.rotate(i * Math.PI*2/3);
ctx.beginPath();
ctx.moveTo(0,0);
ctx.arc(0, 0, r, -Math.PI/5.5, Math.PI/5.5);
ctx.closePath(); ctx.fill(); ctx.restore();
}
ctx.beginPath();
ctx.arc(0, 0, r*0.28, 0, Math.PI*2);
ctx.fillStyle = 'rgba(255,255,255,0.25)'; ctx.fill();
ctx.restore();
}
function drawIcon_anchor(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
ctx.lineWidth = r*0.22;
// Vertical
ctx.beginPath(); ctx.moveTo(0,-r); ctx.lineTo(0,r); ctx.stroke();
// Cross
ctx.beginPath(); ctx.moveTo(-r*0.6,-r*0.35); ctx.lineTo(r*0.6,-r*0.35); ctx.stroke();
// Top knob
ctx.beginPath(); ctx.arc(0,-r,r*0.22,0,Math.PI*2); ctx.fill();
// Curves
ctx.lineWidth = r*0.18;
ctx.beginPath(); ctx.arc(-r*0.48, r*0.18, r*0.52, Math.PI*0.55, Math.PI); ctx.stroke();
ctx.beginPath(); ctx.arc( r*0.48, r*0.18, r*0.52, 0, Math.PI*0.45); ctx.stroke();
ctx.restore();
}
function drawIcon_radar(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
ctx.lineWidth = r*0.16;
for (let i=1; i<=3; i++) {
ctx.beginPath(); ctx.arc(0, r*0.2, r*0.24*i, Math.PI*1.05, Math.PI*1.95); ctx.stroke();
}
ctx.lineWidth = r*0.2;
ctx.beginPath(); ctx.moveTo(0,r*0.2); ctx.lineTo(0,r); ctx.stroke();
ctx.beginPath(); ctx.moveTo(-r*0.3,r); ctx.lineTo(r*0.3,r); ctx.stroke();
ctx.restore();
}
function drawIcon_star(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
ctx.beginPath();
for (let i=0; i<6; i++) {
const a = i*Math.PI/3 - Math.PI/2;
const ia = a + Math.PI/6;
if (i===0) ctx.moveTo(Math.cos(a)*r, Math.sin(a)*r);
else ctx.lineTo(Math.cos(a)*r, Math.sin(a)*r);
ctx.lineTo(Math.cos(ia)*r*0.44, Math.sin(ia)*r*0.44);
}
ctx.closePath(); ctx.fill(); ctx.restore();
}
function drawIcon_lightning(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
ctx.beginPath();
ctx.moveTo( r*0.18, -r);
ctx.lineTo(-r*0.32, -r*0.04);
ctx.lineTo( r*0.08, -r*0.04);
ctx.lineTo(-r*0.2, r);
ctx.lineTo( r*0.38, -r*0.22);
ctx.lineTo(-r*0.05, -r*0.22);
ctx.closePath(); ctx.fill(); ctx.restore();
}
function drawIcon_diamond(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
ctx.beginPath();
ctx.moveTo(0, -r); ctx.lineTo(r*0.65, 0);
ctx.lineTo(0, r); ctx.lineTo(-r*0.65, 0);
ctx.closePath(); ctx.fill(); ctx.restore();
}
function drawIcon_box(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
const s = r*0.72;
ctx.fillRect(-s, -s*0.62, s*2, s*1.4);
ctx.fillStyle = 'rgba(0,0,0,0.15)';
ctx.fillRect(-s*0.82, -s*0.9, s*1.64, s*0.32);
ctx.fillStyle = 'white';
ctx.fillRect(-s*0.82, -s*0.9, s*1.64, s*0.28);
ctx.restore();
}
function drawIcon_tunnel(ctx, cx, cy, r) {
ctx.save(); ctx.translate(cx, cy);
ctx.beginPath();
ctx.moveTo(-r, -r*0.2); ctx.lineTo(0, r); ctx.lineTo(r, -r*0.2);
ctx.closePath(); ctx.fill();
ctx.fillStyle = 'rgba(0,0,0,0.2)';
ctx.beginPath();
ctx.moveTo(-r*0.28, -r*0.32); ctx.lineTo(r*0.28, -r*0.32);
ctx.lineTo(0, -r); ctx.closePath(); ctx.fill();
ctx.restore();
}
function drawIcon_gear(ctx, cx, cy, r) {
const teeth = 8;
ctx.save(); ctx.translate(cx, cy);
ctx.beginPath();
for (let i=0; i<teeth*2; i++) {
const a = i*Math.PI/teeth;
const rad = i%2===0 ? r : r*0.72;
if (i===0) ctx.moveTo(Math.cos(a)*rad, Math.sin(a)*rad);
else ctx.lineTo(Math.cos(a)*rad, Math.sin(a)*rad);
}
ctx.closePath(); ctx.fill();
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath(); ctx.arc(0,0,r*0.34,0,Math.PI*2); ctx.fill();
ctx.restore();
}
function drawIcon_unknown(ctx, cx, cy, r, size) {
ctx.save(); ctx.translate(cx, cy);
ctx.font = `700 ${r*1.3}px "IBM Plex Mono", monospace`;
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText('?', 0, r*0.06);
ctx.restore();
}
// Small icons for list view (canvas elements)
const _listIconCache = {};
function getListIcon(catKey, color) {
const key = catKey + '_' + color;
if (_listIconCache[key]) return _listIconCache[key];
const size = 28;
const c = document.createElement('canvas');
c.width = size * 2; c.height = size * 2;
c.style.width = size + 'px'; c.style.height = size + 'px';
const ctx = c.getContext('2d');
ctx.scale(2, 2);
const cx = size/2, cy = size/2, r = size/2 - 1.5;
ctx.beginPath(); ctx.arc(cx,cy,r,0,Math.PI*2);
ctx.fillStyle = color; ctx.fill();
ctx.strokeStyle = 'rgba(255,255,255,0.7)'; ctx.lineWidth = 1.2; ctx.stroke();
ctx.fillStyle = 'white'; ctx.strokeStyle = 'white'; ctx.lineCap = 'round';
const ir = r * 0.5;
switch(catKey) {
case 'hava': drawIcon_airplane(ctx,cx,cy,ir); break;
case 'nukleer': drawIcon_radiation(ctx,cx,cy,ir); break;
case 'liman': drawIcon_anchor(ctx,cx,cy,ir); break;
case 'radar': drawIcon_radar(ctx,cx,cy,ir); break;
case 'askeri': drawIcon_star(ctx,cx,cy,ir); break;
case 'enerji': drawIcon_lightning(ctx,cx,cy,ir); break;
case 'arastirma': drawIcon_diamond(ctx,cx,cy,ir); break;
case 'depo': drawIcon_box(ctx,cx,cy,ir); break;
case 'tunel': drawIcon_tunnel(ctx,cx,cy,ir); break;
case 'sanayi': drawIcon_gear(ctx,cx,cy,ir); break;
default: drawIcon_unknown(ctx,cx,cy,ir,size); break;
}
_listIconCache[key] = c;
return c;
}
/* ═══════════════════════════════════════════════════════════════
5. MAP INITIALIZATION
═══════════════════════════════════════════════════════════════ */
// MAPBOX TOKEN — Replace with your own for production
mapboxgl.accessToken = '';
let popup = null;
// Performance monitoring
function logPerformanceMetrics() {
if (S.raw.length === 0) return;
const stats = {
totalPoints: S.raw.length,
renderingMethod: 'Mapbox GPU (GeoJSON + Symbol/Circle Layers)',
clusteringEnabled: true,
domElementsCreated: 0, // Zero! All GPU-rendered
memoryEstimate: `${((S.raw.length * 0.5) / 1024).toFixed(2)} MB`,
performanceNote: '10,000+ points @ 60fps without DOM overhead'
};
console.table(stats);
}
function initMap() {
S.map = new mapboxgl.Map({
container: 'map',
style: MAP_STYLES.light,
center: [35.0, 39.0],
zoom: 5.5,
attributionControl: false,
logoPosition: 'bottom-right',
});
S.map.addControl(new mapboxgl.AttributionControl({ compact: true }), 'bottom-right');
popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false,
offset: 14,
maxWidth: '240px',
});
S.map.on('load', () => {
S.mapReady = true;
// Add all category icons to the map
CATS.forEach(cat => {
const icon = genIcon(cat.key, cat.color);
S.map.addImage('icon-' + cat.key, icon, { pixelRatio: ICON_DPR });
});
addMapLayers();
});
// Hover: show popup
S.map.on('mouseenter', 'facilities-circles', (e) => {
S.map.getCanvas().style.cursor = 'pointer';
const f = e.features[0];
const coords = f.geometry.coordinates.slice();
showPopup(coords, f.properties);
});
S.map.on('mouseleave', 'facilities-circles', () => {
S.map.getCanvas().style.cursor = '';
if (popup) popup.remove();
});
// Click: open detail
S.map.on('click', 'facilities-circles', (e) => {
const props = e.features[0].properties;
openDetail(props.ID);
scrollToItem(props.ID);
});
// Click on cluster: zoom in
S.map.on('click', 'clusters', (e) => {
const f = e.features[0];
const clusterId = f.properties.cluster_id;
S.map.getSource('facilities').getClusterExpansionZoom(clusterId, (err, zoom) => {
if (err) return;
S.map.easeTo({ center: f.geometry.coordinates, zoom: zoom + 0.5 });
});
});
S.map.on('mouseenter', 'clusters', () => { S.map.getCanvas().style.cursor = 'pointer'; });
S.map.on('mouseleave', 'clusters', () => { S.map.getCanvas().style.cursor = ''; });
// Mouse move: show coordinates in info bar
S.map.on('mousemove', (e) => {
const el = document.getElementById('map-info');
el.style.display = 'block';
el.textContent = `${e.lngLat.lat.toFixed(4)}°N ${e.lngLat.lng.toFixed(4)}°E`;
});
S.map.on('mouseleave', () => {
document.getElementById('map-info').style.display = 'none';
});
}
function addMapLayers() {
// GPU RENDERING ARCHITECTURE
// Layer 1: GeoJSON Clustering (Mapbox built-in) — groups points for zoom levels
// Layer 2: Cluster circles + labels (symbol/circle type) — fast GPU rendering
// Layer 3: Individual point circles (invisible, z-order/interaction) — hitbox layer
// Layer 4: Individual icon symbols (GPU rasterized) — visual representation
// RESULT: 10,000+ points render at 60fps with ZERO DOM elements
if (!S.map.getSource('facilities')) {
S.map.addSource('facilities', {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] },
cluster: true,
clusterMaxZoom: 11,
clusterRadius: 45,
clusterMinPoints: 3,
});
}
// Cluster background circles
if (!S.map.getLayer('clusters')) {
S.map.addLayer({
id: 'clusters',
type: 'circle',
source: 'facilities',
filter: ['has', 'point_count'],
paint: {
'circle-color': [
'step', ['get', 'point_count'],
'#5C6BC0', 10,
'#E53935', 30,
'#B71C1C',
],
'circle-radius': ['step', ['get', 'point_count'], 18, 10, 24, 30, 32],
'circle-opacity': 0.88,
'circle-stroke-width': 2,
'circle-stroke-color': 'white',
},
});
// Cluster count labels
S.map.addLayer({
id: 'cluster-count',
type: 'symbol',
source: 'facilities',
filter: ['has', 'point_count'],
layout: {
'text-field': '{point_count_abbreviated}',
'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
'text-size': 12,
},
paint: { 'text-color': '#ffffff' },
});
// HITBOX LAYER — Invisible circles for mouse interaction
// Why? Symbol layers don't have reliable feature detection for hover/click
// This circle layer (opacity 0.0) serves as the interaction target
// GPU handles all rendering - no DOM elements, no event listeners per point
S.map.addLayer({
id: 'facilities-circles',
type: 'circle',
source: 'facilities',
filter: ['!', ['has', 'point_count']],
paint: {
'circle-radius': [
'step', ['get', 'Kritiklik'],
5, 34, 8, 67, 11 // Radius scales by criticality
],
'circle-color': buildCatColorExpression(),
'circle-opacity': [
'case', ['==', ['get', 'Durum'], 'PASİF'], 0.3, 0.0 // Invisible but interactive
],
'circle-stroke-width': 0,
},
});
// ICON LAYER — Canvas-pre-rendered category icons
// All icons generated once at load → cached → uploaded to GPU via addImage()
// Symbol layer renders them at vector scale with zero additional CPU cost
// Icon size scales by criticality for visual importance feedback
S.map.addLayer({
id: 'facilities-icons',
type: 'symbol',
source: 'facilities',
filter: ['!', ['has', 'point_count']],
layout: {
'icon-image': buildCatIconExpression(), // Match expression to category
'icon-size': ['step', ['get', 'Kritiklik'], 0.58, 34, 0.78, 67, 1.0], // Scale by importance
'icon-allow-overlap': false,
'icon-ignore-placement': false,
},
paint: {
'icon-opacity': ['case', ['==', ['get', 'Durum'], 'PASİF'], 0.3, 0.9], // Dim PASİF
},
});
}
}
function buildCatColorExpression() {
const expr = ['match', ['get', 'categoryType']];
CATS.forEach(c => { expr.push(c.key); expr.push(c.color); });
expr.push('#9E9E9E'); // fallback
return expr;
}
function buildCatIconExpression() {
const expr = ['match', ['get', 'categoryType']];
CATS.forEach(c => { expr.push(c.key); expr.push('icon-' + c.key); });
expr.push('icon-unknown');
return expr;
}
function showPopup(coords, props) {
const cat = catByKey(props.categoryType);
const critC = critColor(+props.Kritiklik || 0);
popup.setLngLat(coords)
.setHTML(`
<div class="popup-id">#${props.ID}</div>
<div class="popup-name">${props['Tesis Adı'] || props['Tesis_Adı'] || '—'}</div>
<div class="popup-sub" style="color:${cat.color}">${cat.label} · ${props.Durum || ''}</div>
<div class="popup-crit">
<div class="popup-crit-bar">
<div class="popup-crit-fill" style="width:${props.Kritiklik||0}%;background:${critC}"></div>
</div>
<span class="popup-crit-val">${props.Kritiklik || 0}/100</span>
</div>
`)
.addTo(S.map);
}
/* ═══════════════════════════════════════════════════════════════
6. DATA PIPELINE
═══════════════════════════════════════════════════════════════ */
function processCSV(rows) {
setLoading(true);
S.raw = [];
S.catCounts = {};
S.statusSet = new Set();
let validCount = 0;
let invalidCount = 0;
rows.forEach((row, idx) => {
// VALIDATION: Coordinates are mandatory for mapping
const lat = parseFloat(row['Enlem'] ?? row['enlem'] ?? row['lat'] ?? row['Lat'] ?? row['latitude'] ?? row['Latitude']);
const lng = parseFloat(row['Boylam'] ?? row['boylam'] ?? row['lng'] ?? row['Lng'] ?? row['lon'] ?? row['longitude'] ?? row['Longitude']);
if (isNaN(lat) || isNaN(lng)) {
invalidCount++;
return; // Skip invalid rows
}
const catKey = detectCat(row['Kategori'] || '');
const kritValue = parseInt(row['Kritiklik']) || 0;
// VALIDATION: Criticality score bounds
const krit = Math.min(100, Math.max(0, kritValue));
if (kritValue < 0 || kritValue > 100) {
console.warn(`Row ${idx}: Criticality adjusted from ${kritValue} to ${krit}`);
}
const durum = (row['Durum'] || '').trim() || 'KONTROL ET';
row._cat = catKey;
row._krit = krit;
row._lat = lat;
row._lng = lng;
row._durum = durum;
S.raw.push(row);
S.catCounts[catKey] = (S.catCounts[catKey] || 0) + 1;
S.statusSet.add(durum);
validCount++;
});
// Validation report
if (invalidCount > 0) {
console.warn(`⚠ Dataset validation: ${validCount} valid, ${invalidCount} invalid rows skipped`);
}
// Initialize active sets
S.activeCats = new Set(CATS.map(c => c.key));
S.activeStatuses = new Set(S.statusSet);
S.critRange = [0, 100];
// Performance logging
console.log(`\n✅ Data processing complete:`);
console.log(` Valid records: ${validCount} | Invalid skipped: ${invalidCount}`);
console.log(` Categories detected: ${Object.keys(S.catCounts).length}`);
console.log(` Unique statuses: ${S.statusSet.size}`);
console.log(` GPU memory estimate: ~${((validCount * 0.5) / 1024).toFixed(2)} MB\n`);
// Build and load GeoJSON into map
pushGeoJSON();
// Update UI
buildStatusChips();
buildCatFilter();
buildLegend();
updateStats();
// Filter + render list
applyFilters();
// Fit bounds
if (S.raw.length > 0) fitMapBounds();
setLoading(false);
document.getElementById('upload-overlay').style.display = 'none';
}
function buildGeoJSON(features_array) {
return {
type: 'FeatureCollection',
features: features_array,
};
}
function rowToFeature(row) {
return {
type: 'Feature',
geometry: { type: 'Point', coordinates: [row._lng, row._lat] },
properties: {
ID: row['ID'] || '',
'Tesis Adı': row['Tesis Adı'] || '',
Kategori: row['Kategori'] || '',
Kritiklik: row._krit,
Durum: row._durum,
Kaynak: row['Kaynak'] || '',
Etiket: row['Etiket'] || '',
Tahmini_Alan_km2: row['Tahmini_Alan_km2'] || '',
Detayli_Stratejik_Aciklama: row['Detayli_Stratejik_Aciklama'] || '',
categoryType: row._cat,
_lat: row._lat,
_lng: row._lng,
},
};
}
function pushGeoJSON() {
if (!S.mapReady) {
S.map.once('load', () => pushGeoJSON());
return;
}
const features = S.raw.map(rowToFeature);
const gj = buildGeoJSON(features);
if (S.map.getSource('facilities')) {
S.map.getSource('facilities').setData(gj);
}
}
function fitMapBounds() {
if (S.raw.length === 0) return;
let minLat = Infinity, maxLat = -Infinity;
let minLng = Infinity, maxLng = -Infinity;
S.raw.forEach(r => {
minLat = Math.min(minLat, r._lat); maxLat = Math.max(maxLat, r._lat);
minLng = Math.min(minLng, r._lng); maxLng = Math.max(maxLng, r._lng);
});
S.map.fitBounds([[minLng, minLat],[maxLng, maxLat]], { padding: 60, duration: 1200 });
}
/* ═══════════════════════════════════════════════════════════════
7. FILTER ENGINE
═══════════════════════════════════════════════════════════════ */
let _filterTimer = null;
function applyFilters() {
const q = S.search.toLowerCase();
S.filtered = S.raw.filter(row => {
// Category
if (!S.activeCats.has(row._cat)) return false;
// Status
if (!S.activeStatuses.has(row._durum)) return false;
// Criticality
if (row._krit < S.critRange[0] || row._krit > S.critRange[1]) return false;
// Search
if (q) {
const id = String(row['ID'] || '').toLowerCase();
const name = String(row['Tesis Adı'] || '').toLowerCase();
const tag = String(row['Etiket'] || '').toLowerCase();
const desc = String(row['Detayli_Stratejik_Aciklama'] || '').toLowerCase();
if (!id.includes(q) && !name.includes(q) && !tag.includes(q) && !desc.includes(q)) return false;
}
return true;
});
// Sort
S.filtered.sort((a, b) => {
const av = a[S.sortField] ?? a['_krit'] ?? 0;
const bv = b[S.sortField] ?? b['_krit'] ?? 0;
if (typeof av === 'number') return S.sortDir * (bv - av);
return S.sortDir * String(av).localeCompare(String(bv));
});
// Update map filter
updateMapFilter();
// Update list
updateListCount();
resetVS();
renderVS();
// Update visible stat
document.getElementById('stat-visible').textContent = S.filtered.length;
}
function updateMapFilter() {
if (!S.mapReady || !S.map.getLayer('facilities-circles')) return;
const filteredIds = new Set(S.filtered.map(r => String(r['ID'])));
const allIds = S.filtered.map(r => String(r['ID']));
let mapFilter;
if (S.filtered.length === S.raw.length) {
// Show all unclustered
mapFilter = ['!', ['has', 'point_count']];
} else {
mapFilter = ['all',
['!', ['has', 'point_count']],
['in', ['to-string', ['get', 'ID']], ['literal', allIds]],
];
}
S.map.setFilter('facilities-circles', mapFilter);
S.map.setFilter('facilities-icons', mapFilter);
}
/* ═══════════════════════════════════════════════════════════════
8. VIRTUAL SCROLL LIST
═══════════════════════════════════════════════════════════════ */
const listScroll = document.getElementById('list-scroll');
const listInner = document.getElementById('list-inner');
const listEmpty = document.getElementById('list-empty');
let _topSpacer = document.createElement('div');
let _bottomSpacer = document.createElement('div');
listInner.appendChild(_topSpacer);
listInner.appendChild(_bottomSpacer);
function resetVS() {
S.vs.start = 0;
listScroll.scrollTop = 0;
}
function renderVS() {
const total = S.filtered.length;
const scrollH = listScroll.clientHeight || 400;
const top = listScroll.scrollTop;
const startIdx = Math.max(0, Math.floor(top / ITEM_H) - OVERSCAN);
const endIdx = Math.min(total, Math.ceil((top + scrollH) / ITEM_H) + OVERSCAN);
S.vs.start = startIdx;
S.vs.end = endIdx;
const topPad = startIdx * ITEM_H;
const bottomPad = Math.max(0, (total - endIdx) * ITEM_H);
_topSpacer.style.height = topPad + 'px';
_bottomSpacer.style.height = bottomPad + 'px';
// Clear old rendered items (between spacers)
while (listInner.children.length > 2) {
listInner.removeChild(listInner.children[1]);
}
if (total === 0) {
listEmpty.style.display = 'block';
return;
}
listEmpty.style.display = 'none';
const frag = document.createDocumentFragment();
for (let i = startIdx; i < endIdx; i++) {
frag.appendChild(buildListItem(S.filtered[i]));
}
listInner.insertBefore(frag, _bottomSpacer);
}
function buildListItem(row) {
const cat = catByKey(row._cat);
const critC = critColor(row._krit);
const statC = statusColor(row._durum);
const isSelected = String(row['ID']) === String(S.selectedId);
const el = document.createElement('div');
el.className = 'li' + (isSelected ? ' sel' : '');
el.dataset.id = row['ID'];
el.style.height = ITEM_H + 'px';
const icon = getListIcon(row._cat, cat.color);
const iconClone = icon.cloneNode(false);
iconClone.width = icon.width;
iconClone.height = icon.height;
iconClone.style.width = '28px';
iconClone.style.height = '28px';
// Copy canvas content
const ictx = iconClone.getContext('2d');
ictx.drawImage(icon, 0, 0);
el.innerHTML = `
<div class="li-icon"></div>
<div class="li-body">
<div class="li-id">#${row['ID']}</div>
<div class="li-name" title="${row['Tesis Adı'] || ''}">${row['Tesis Adı'] || '—'}</div>
<div class="li-meta">
<span class="li-status" style="background:${statC}22;color:${statC}">${row._durum}</span>
<div class="li-crit-wrap"><div class="li-crit-bar" style="width:${row._krit}%;background:${critC}"></div></div>
<span class="li-crit-val">${row._krit}</span>
</div>
</div>
`;
el.querySelector('.li-icon').appendChild(iconClone);
el.addEventListener('click', () => {
openDetail(row['ID']);
flyToFacility(row);
});
return el;
}
function updateListCount() {
document.getElementById('list-count').textContent =
`${S.filtered.length} / ${S.raw.length} tesis`;
}
function scrollToItem(id) {
const idx = S.filtered.findIndex(r => String(r['ID']) === String(id));
if (idx < 0) return;
listScroll.scrollTop = idx * ITEM_H;
renderVS();
}
listScroll.addEventListener('scroll', () => {
renderVS();
}, { passive: true });
/* ═══════════════════════════════════════════════════════════════
9. DETAIL PANEL
═══════════════════════════════════════════════════════════════ */
function openDetail(id) {
const row = S.raw.find(r => String(r['ID']) === String(id));
if (!row) return;
S.selectedId = id;
const cat = catByKey(row._cat);
const critC = critColor(row._krit);
const statC = statusColor(row._durum);
document.getElementById('d-id').textContent = '#' + row['ID'];
document.getElementById('d-name').textContent = row['Tesis Adı'] || '—';
document.getElementById('d-desc').textContent = row['Detayli_Stratejik_Aciklama'] || '—';
document.getElementById('d-coords').textContent = `${row._lat.toFixed(5)}°N ${row._lng.toFixed(5)}°E`;
document.getElementById('d-cat').textContent = cat.label;
document.getElementById('d-status').innerHTML = `<span style="color:${statC};font-family:var(--mono);font-size:12px;font-weight:600">${row._durum}</span>`;
document.getElementById('d-source').textContent = row['Kaynak'] || '—';
document.getElementById('d-area').textContent = row['Tahmini_Alan_km2'] ? row['Tahmini_Alan_km2'] + ' km²' : '—';
document.getElementById('detail-stripe').style.background = cat.color;
document.getElementById('d-crit-bar').style.width = row._krit + '%';
document.getElementById('d-crit-bar').style.background = critC;
document.getElementById('d-crit-val').textContent = row._krit + '/100';
// Tags
const tagsEl = document.getElementById('d-tags');
tagsEl.innerHTML = '';
const tags = (row['Etiket'] || '').split(/[,;\/]/).map(t => t.trim()).filter(Boolean);
if (tags.length === 0) {
tagsEl.innerHTML = '<span style="color:var(--tm);font-family:var(--mono);font-size:10px">—</span>';
} else {
tags.forEach(t => {
const span = document.createElement('span');
span.className = 'tag'; span.textContent = t;
tagsEl.appendChild(span);
});
}
document.getElementById('detail').classList.add('open');
// Highlight list item
document.querySelectorAll('.li').forEach(el => {
el.classList.toggle('sel', el.dataset.id === String(id));
});
}
function closeDetail() {
document.getElementById('detail').classList.remove('open');
S.selectedId = null;
document.querySelectorAll('.li').forEach(el => el.classList.remove('sel'));
}
function flyToFacility(row) {
if (!S.mapReady) return;
S.map.flyTo({
center: [row._lng, row._lat],
zoom: Math.max(S.map.getZoom(), 10),
duration: 900,
essential: true,
});
}
/* ═══════════════════════════════════════════════════════════════
10. STATS
═══════════════════════════════════════════════════════════════ */
function updateStats() {
const total = S.raw.length;
const highCrit = S.raw.filter(r => r._krit > 66).length;
const catCount = Object.keys(S.catCounts).filter(k => S.catCounts[k] > 0).length;
document.getElementById('stat-total').textContent = total;
document.getElementById('stat-cats').textContent = catCount;
document.getElementById('stat-high').textContent = highCrit;
document.getElementById('stat-visible').textContent = total;
}
/* ═══════════════════════════════════════════════════════════════
11. FILTER UI BUILDERS
═══════════════════════════════════════════════════════════════ */
function buildStatusChips() {
const container = document.getElementById('status-chips');
container.innerHTML = '';
[...S.statusSet].sort().forEach(status => {
const chip = document.createElement('button');
chip.className = 'chip on';
chip.textContent = status;
chip.dataset.status = status;
chip.style.borderLeftColor = statusColor(status);
chip.addEventListener('click', () => {
chip.classList.toggle('on');
if (chip.classList.contains('on')) S.activeStatuses.add(status);
else S.activeStatuses.delete(status);
scheduleFilter();
});
container.appendChild(chip);
});
}
function buildCatFilter() {
const container = document.getElementById('cat-list');
container.innerHTML = '';
CATS.forEach(cat => {
const cnt = S.catCounts[cat.key] || 0;
if (cnt === 0) return;
const row = document.createElement('div');
row.className = 'cat-row on';
row.dataset.cat = cat.key;
row.innerHTML = `
<div class="cat-check"></div>
<div class="cat-swatch" style="background:${cat.color}"></div>
<div class="cat-name">${cat.label}</div>
<div class="cat-cnt">${cnt}</div>
`;
row.addEventListener('click', () => {
row.classList.toggle('on');
if (row.classList.contains('on')) S.activeCats.add(cat.key);
else S.activeCats.delete(cat.key);
scheduleFilter();
});
container.appendChild(row);
});
}
function buildLegend() {