-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
3313 lines (3123 loc) · 210 KB
/
index.tsx
File metadata and controls
3313 lines (3123 loc) · 210 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
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { createRoot } from 'react-dom/client';
import { GoogleGenAI, Type, Chat, GenerateContentResponse } from "@google/genai";
import * as d3 from "d3";
import Markdown from 'react-markdown';
import { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, WidthType, AlignmentType, HeadingLevel } from 'docx';
import { saveAs } from 'file-saver';
import './index.css';
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
Tooltip as RechartsTooltip,
ResponsiveContainer,
PieChart,
Pie,
Cell,
Legend
} from 'recharts';
import {
Activity,
ChevronRight,
DatabaseZap,
Network,
List,
Loader2,
Globe2,
ArrowRight,
Share2,
Sun,
Moon,
BarChart3,
FlaskConical,
LogOut,
ShieldCheck,
Send,
MessageSquare,
Atom,
Search,
Info,
ChevronDown,
ChevronUp,
Layers,
BookOpen,
ExternalLink,
FileText,
Pill,
Stethoscope,
Users,
Building2,
ZoomIn,
ZoomOut,
RotateCcw,
PanelLeft,
PanelRight,
Database,
ChevronLeft,
CheckCircle2,
TrendingUp,
TrendingDown,
Volume2,
Microscope,
AlertCircle,
Flag,
Maximize,
TableProperties,
Plus,
ArrowUpDown,
HelpCircle,
X,
FileDown,
ThumbsUp,
ThumbsDown,
Pin,
Save,
Trash2,
Home
} from 'lucide-react';
import {
Target,
DrugInfo,
DiseaseInfo,
EnrichmentResult,
PubMedStats,
Theme,
ViewMode,
TerrainLayer,
ResearchContext,
Message,
ClinicalSample,
ExpressionRow,
SurvivalMetrics
} from './types';
import {
vertexShaderSource,
terrainFragmentShader,
contourFragmentShader,
peaksFragmentShader,
valleyFragmentShader
} from './shaders';
import { api } from './api';
// --- Configuration ---
const HARDCODED_PASSWORD = "Sparc@2026";
const MAX_WebGL_POINTS = 1024;
const DEMO_PATIENTS = [
{ id: 'P1', race: 'WHITE', stage: 'Stage I', os_time: 1200 },
{ id: 'P2', race: 'WHITE', stage: 'Stage II', os_time: 800 },
{ id: 'P3', race: 'BLACK', stage: 'Stage I', os_time: 1100 },
{ id: 'P4', race: 'BLACK', stage: 'Stage III', os_time: 600 },
{ id: 'P5', race: 'ASIAN', stage: 'Stage II', os_time: 950 },
{ id: 'P6', race: 'OTHER', stage: 'Stage IV', os_time: 400 },
];
const getDemoExpression = (symbol: string, patientId: string) => {
let hash = 0;
const str = symbol + patientId;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash |= 0;
}
return (Math.abs(hash % 100) / 100);
};
const CANCER_TYPE_MAP: Record<string, string> = {
'bladder': 'BLCA',
'breast': 'BRCA',
'cervical': 'CESC',
'cholangiocarcinoma': 'CHOL',
'kidney': 'KIRC',
'brca': 'BRCA',
'blca': 'BLCA',
'cesc': 'CESC',
'chol': 'CHOL',
'kirc': 'KIRC'
};
const detectCancerType = (name: string) => {
const lowerName = name.toLowerCase();
for (const [key, code] of Object.entries(CANCER_TYPE_MAP)) {
if (lowerName.includes(key)) return code;
}
return null;
};
// --- Helper Components for Visualization ---
const RadarChart = ({ target, theme }: { target: Target, theme: Theme }) => {
const size = 260;
const center = size / 2;
const radius = size * 0.35;
const axes = [
{ label: 'Genetic', val: target.geneticScore, color: 'text-blue-500', bg: 'bg-blue-500/10' },
{ label: 'Literature', val: target.literatureScore || 0, color: 'text-purple-500', bg: 'bg-purple-500/10' },
{ label: 'GET Score', val: target.getScore || 0, color: 'text-indigo-500', bg: 'bg-indigo-500/10' },
{ label: 'Expression', val: target.combinedExpression || 0, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
{ label: 'Target', val: target.targetScore || 0, color: 'text-amber-500', bg: 'bg-amber-500/10' },
{ label: 'Priority', val: target.overallScore, color: 'text-blue-600', bg: 'bg-blue-600/10' }
];
const points = axes.map((a, i) => {
const angle = (Math.PI * 2 * i) / axes.length - Math.PI / 2;
const x = center + radius * a.val * Math.cos(angle);
const y = center + radius * a.val * Math.sin(angle);
return `${x},${y}`;
}).join(' ');
const gridLevels = [0.25, 0.5, 0.75, 1.0];
return (
<div className="flex flex-col lg:flex-row items-center gap-12 w-full">
<div className="relative">
<svg width={size} height={size} className="overflow-visible">
{/* Grids */}
{gridLevels.map(level => (
<circle
key={level}
cx={center}
cy={center}
r={radius * level}
fill="none"
stroke={theme === 'dark' ? '#334155' : '#cbd5e1'}
strokeDasharray="2,2"
/>
))}
{/* Axes */}
{axes.map((a, i) => {
const angle = (Math.PI * 2 * i) / axes.length - Math.PI / 2;
const x2 = center + radius * Math.cos(angle);
const y2 = center + radius * Math.sin(angle);
return (
<g key={i}>
<line x1={center} y1={center} x2={x2} y2={y2} stroke={theme === 'dark' ? '#334155' : '#cbd5e1'} />
<text
x={center + (radius + 25) * Math.cos(angle)}
y={center + (radius + 20) * Math.sin(angle)}
textAnchor="middle"
fontSize="8"
fontWeight="bold"
className={theme === 'dark' ? 'fill-neutral-500' : 'fill-neutral-600'}
>
{a.label}
</text>
</g>
);
})}
{/* Data Shape */}
<polygon
points={points}
fill="rgba(59, 130, 246, 0.3)"
stroke="#3b82f6"
strokeWidth="2"
/>
</svg>
</div>
<div className="flex-1 grid grid-cols-2 gap-3">
{axes.map((a, i) => (
<div
key={i}
className={`flex flex-col p-3 rounded-xl border transition-all hover:scale-105 ${theme === 'dark' ? 'bg-[#1c1c1c] border-neutral-800' : 'bg-white border-neutral-100 shadow-sm'}`}
>
<span className="text-[9px] font-bold uppercase text-neutral-400 tracking-widest mb-1">{a.label}</span>
<div className="flex items-center justify-between">
<span className={`text-lg font-black ${a.color}`}>{a.val.toFixed(3)}</span>
<div className={`px-1.5 py-0.5 rounded text-[8px] font-bold ${a.bg} ${a.color}`}>SCORE</div>
</div>
</div>
))}
</div>
</div>
);
};
const PipelineProgress = ({ phase }: { phase: number }) => {
const steps = [1, 2, 3, 4];
return (
<div className="flex items-center gap-1 w-full max-w-[120px]">
{steps.map(s => (
<div
key={s}
className={`h-1.5 flex-1 rounded-full transition-all ${s <= phase ? 'bg-blue-500 shadow-[0_0_8px_rgba(59,130,246,0.4)]' : 'bg-neutral-200 dark:bg-neutral-800'}`}
title={`Phase ${s}`}
/>
))}
</div>
);
};
const PublicationSparkline = ({ recent, total, theme }: { recent: number, total: number, theme: Theme }) => {
// Mock sparkline based on recent vs total
const width = 140;
const height = 30;
const points = [5, 12, 8, 15, 10, 22, 14, recent > 0 ? 25 : 12];
const step = width / (points.length - 1);
const path = points.map((p, i) => `${i * step},${height - p}`).join(' L ');
return (
<div className="relative">
<svg width={width} height={height} className="overflow-visible">
<path
d={`M 0,${height} L ${path} L ${width},${height} Z`}
fill="url(#sparkline-grad)"
opacity="0.2"
/>
<path
d={`M 0,${height - points[0]} L ${path}`}
fill="none"
stroke="#3b82f6"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<defs>
<linearGradient id="sparkline-grad" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#3b82f6" />
<stop offset="100%" stopColor="transparent" />
</linearGradient>
</defs>
</svg>
</div>
);
};
// --- Force Directed Layout Utilities ---
function pearson(a: number[], b: number[]) {
const n = Math.min(a.length, b.length);
if (n === 0) return 0;
let sumA = 0, sumB = 0, sumAA = 0, sumBB = 0, sumAB = 0;
for (let i = 0; i < n; i++) {
const x = a[i], y = b[i];
sumA += x; sumB += y;
sumAA += x * x; sumBB += y * y; sumAB += x * y;
}
const num = n * sumAB - sumA * sumB;
const den = Math.sqrt((n * sumAA - sumA * sumA) * (n * sumBB - sumB * sumB));
if (!isFinite(den) || den === 0) return 0;
return num / den;
}
function getGetVector(t: Target) {
return [t.geneticScore ?? 0, t.combinedExpression ?? 0, t.targetScore ?? 0];
}
function computeForcePositions(targets: Target[], width = 800, height = 600) {
const nodes = targets.map((t, i) => ({
id: t.id,
symbol: t.symbol,
r: 6 + (t.overallScore * 6),
x: width / 2 + Math.cos(i) * 50,
y: height / 2 + Math.sin(i) * 50
}));
const vectors = targets.map(getGetVector);
const links: any[] = [];
for (let i = 0; i < targets.length; i++) {
for (let j = i + 1; j < targets.length; j++) {
const r = pearson(vectors[i], vectors[j]);
links.push({ source: targets[i].id, target: targets[j].id, weight: Math.abs(r), sign: r });
}
}
const sim = (d3 as any).forceSimulation(nodes as any)
.force("link", (d3 as any).forceLink(links).id((d: any) => d.id)
.strength((l: any) => 0.05 + 0.45 * (l.weight ?? 0))
.distance((l: any) => 300 * (1 - (l.weight ?? 0)) + 40))
.force("charge", (d3 as any).forceManyBody().strength(-150))
.force("collide", (d3 as any).forceCollide((d: any) => d.r + 10))
.force("center", (d3 as any).forceCenter(width / 2, height / 2));
for (let i = 0; i < 300; i++) sim.tick();
sim.stop();
const xs = nodes.map(n => n.x), ys = nodes.map(n => n.y);
const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys);
const padding = 0.05, rangeX = (maxX - minX) || 1, rangeY = (maxY - minY) || 1;
const posMap = new Map<string, { x: number, y: number, nx: number, ny: number }>();
nodes.forEach((n: any) => {
const nx = padding + (1 - 2 * padding) * (n.x - minX) / rangeX;
const ny = padding + (1 - 2 * padding) * (n.y - minY) / rangeY;
posMap.set(n.id, { x: nx * width, y: ny * height, nx, ny });
});
return { positionsById: posMap, links };
}
const isPointInCircle = (px: number, py: number, cx: number, cy: number, r: number) => {
return Math.sqrt((px - cx) ** 2 + (py - cy) ** 2) < r;
};
const getSigmaForZoom = (scale: number) => 35 / scale;
const CorrelationView = ({ targets, theme }: { targets: Target[], theme: Theme }) => {
const correlations = useMemo(() => {
const pairs: { a: Target, b: Target, r: number, absR: number }[] = [];
const vectors = targets.map(getGetVector);
for (let i = 0; i < targets.length; i++) {
for (let j = i + 1; j < targets.length; j++) {
const r = pearson(vectors[i], vectors[j]);
pairs.push({ a: targets[i], b: targets[j], r, absR: Math.abs(r) });
}
}
return pairs.sort((a, b) => b.absR - a.absR);
}, [targets]);
return (
<div className="h-full overflow-auto">
<table className="w-full text-left">
<thead className={`sticky top-0 z-10 text-[10px] font-bold uppercase tracking-widest border-b ${theme === 'dark' ? 'bg-[#171717] border-neutral-800 text-neutral-500' : 'bg-neutral-50 border-neutral-200 text-neutral-700'}`}>
<tr><th className="p-4 pl-8">Target A</th><th className="p-4">Target B</th><th className="p-4 text-center">Direction</th><th className="p-4 text-center">R Value</th><th className="p-4 pr-8 text-right">Abs. Correlation</th></tr>
</thead>
<tbody className="divide-y divide-neutral-100 dark:divide-neutral-800">
{correlations.map((p, idx) => (
<tr key={`${p.a.id}-${p.b.id}`} className="hover:bg-neutral-50/50 dark:hover:bg-neutral-800/20 transition-colors">
<td className="p-4 pl-8 font-bold text-blue-600 dark:text-blue-500 text-[13px]">{p.a.symbol}</td>
<td className="p-4 font-bold text-blue-600 dark:text-blue-500 text-[13px]">{p.b.symbol}</td>
<td className="p-4 text-center"><span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold uppercase ${p.r >= 0 ? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400' : 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'}`}>{p.r >= 0 ? <TrendingUp className="w-2.5 h-2.5" /> : <TrendingDown className="w-2.5 h-2.5" />}{p.r >= 0 ? 'Positive' : 'Negative'}</span></td>
<td className={`p-4 text-center font-mono text-[11px] ${theme === 'dark' ? 'text-neutral-500' : 'text-neutral-600'}`}>{p.r.toFixed(4)}</td>
<td className="p-4 pr-8 text-right font-mono font-bold text-neutral-800 dark:text-neutral-300 text-[12px]">{p.absR.toFixed(4)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
const KnowledgeGraph = ({ targets, selectedId, onSelect, theme }: { targets: Target[], selectedId?: string, onSelect: (t: Target | null) => void, theme: Theme }) => {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const [transform, setTransform] = useState({ x: 0, y: 0, k: 1 });
const { positionsById, links } = useMemo(() => computeForcePositions(targets, 800, 600), [targets]);
useEffect(() => {
const canvas = canvasRef.current; if (!canvas || !containerRef.current) return;
const ctx = canvas.getContext('2d'); if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const rect = containerRef.current.getBoundingClientRect();
canvas.width = rect.width * dpr; canvas.height = rect.height * dpr;
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, rect.width, rect.height);
ctx.save(); ctx.translate(transform.x, transform.y); ctx.scale(transform.k, transform.k);
const scaleX = rect.width / 800, scaleY = rect.height / 600, baseScale = Math.min(scaleX, scaleY);
links.forEach(l => {
if (l.weight < 0.3) return;
const s = positionsById.get(typeof l.source === 'string' ? l.source : l.source.id);
const t = positionsById.get(typeof l.target === 'string' ? l.target : l.target.id);
if (s && t) {
ctx.beginPath(); ctx.moveTo(s.x * baseScale, s.y * baseScale); ctx.lineTo(t.x * baseScale, t.y * baseScale);
const rgb = l.sign >= 0 ? '239, 68, 68' : '59, 130, 246';
ctx.strokeStyle = `rgba(${rgb}, ${0.05 + l.weight * 0.15})`;
ctx.lineWidth = (0.5 + l.weight * 2.5) / transform.k;
ctx.stroke();
}
});
targets.forEach(t => {
const pos = positionsById.get(t.id); if (!pos) return;
const isSel = t.symbol === selectedId;
const r = 6 + (t.overallScore * 6);
ctx.beginPath(); ctx.arc(pos.x * baseScale, pos.y * baseScale, isSel ? r + 3 : r, 0, Math.PI * 2);
ctx.fillStyle = isSel ? '#3b82f6' : (theme === 'dark' ? '#334155' : '#94a3b8');
ctx.fill();
if (isSel || (t.overallScore > 0.6 && transform.k > 0.5)) {
ctx.fillStyle = theme === 'dark' ? '#f1f5f9' : '#0f172a';
ctx.font = `500 ${10 / transform.k}px Inter`; ctx.textAlign = 'center';
ctx.fillText(t.symbol, pos.x * baseScale, pos.y * baseScale + r + (14 / transform.k));
}
});
ctx.restore();
}, [targets, selectedId, theme, positionsById, links, transform]);
return (
<div ref={containerRef} className="w-full h-full relative bg-transparent overflow-hidden" onWheel={e => { e.preventDefault(); setTransform(prev => ({ ...prev, k: Math.max(0.1, Math.min(10, prev.k * (e.deltaY > 0 ? 0.9 : 1.1))) })); }} onMouseDown={e => {
const startX = e.clientX, startY = e.clientY, startTx = transform.x, startTy = transform.y;
const onMouseMove = (me: MouseEvent) => setTransform(prev => ({ ...prev, x: startTx + (me.clientX - startX), y: startTy + (me.clientY - startY) }));
const onMouseUp = () => { window.removeEventListener('mousemove', onMouseMove); window.removeEventListener('mouseup', onMouseUp); };
window.addEventListener('mousemove', onMouseMove); window.addEventListener('mouseup', onMouseUp);
}}>
<canvas ref={canvasRef} className="w-full h-full cursor-grab active:cursor-grabbing" onClick={(e) => {
const rect = canvasRef.current!.getBoundingClientRect();
const mx = (e.clientX - rect.left - transform.x) / transform.k, my = (e.clientY - rect.top - transform.y) / transform.k;
const scaleX = rect.width / 800, scaleY = rect.height / 600, baseScale = Math.min(scaleX, scaleY);
const hit = targets.find(t => { const pos = positionsById.get(t.id); return pos && isPointInCircle(mx, my, pos.x * baseScale, pos.y * baseScale, 20 / transform.k); });
onSelect(hit || null);
}}/>
<div className="absolute top-6 right-6 flex flex-col gap-2">
<button onClick={() => setTransform(prev => ({ ...prev, k: prev.k * 1.2 }))} className={`p-2 rounded-md border shadow-sm ${theme === 'dark' ? 'bg-[#171717] border-neutral-800 text-neutral-400' : 'bg-white border-neutral-200 text-neutral-600'} hover:bg-neutral-50 transition-colors`}><ZoomIn className="w-4 h-4" /></button>
<button onClick={() => setTransform(prev => ({ ...prev, k: prev.k * 0.8 }))} className={`p-2 rounded-md border shadow-sm ${theme === 'dark' ? 'bg-[#171717] border-neutral-800 text-neutral-400' : 'bg-white border-neutral-200 text-neutral-600'} hover:bg-neutral-50 transition-colors`}><ZoomOut className="w-4 h-4" /></button>
<button onClick={() => setTransform({ x: 0, y: 0, k: 1 })} className={`p-2 rounded-md border shadow-sm ${theme === 'dark' ? 'bg-[#171717] border-neutral-800 text-neutral-400' : 'bg-white border-neutral-200 text-neutral-600'} hover:bg-neutral-50 transition-colors`}><Maximize className="w-4 h-4" /></button>
</div>
</div>
);
};
const GeneTerrain = ({ targets, onSelect, selectedId, theme, mode = 'default', survivalMetrics, medianOs }: { targets: Target[], onSelect: (t: Target | null) => void, selectedId: string | undefined, theme: Theme, mode?: 'default' | 'survival', survivalMetrics?: SurvivalMetrics, medianOs?: number }) => {
const glCanvasRef = useRef<HTMLCanvasElement>(null);
const overlayCanvasRef = useRef<HTMLCanvasElement>(null);
const glRef = useRef<WebGLRenderingContext | null>(null);
const shadersRef = useRef<{ [key: string]: WebGLProgram }>({});
const pointsTexRef = useRef<WebGLTexture | null>(null);
const valuesTexRef = useRef<WebGLTexture | null>(null);
const bufferRef = useRef<WebGLBuffer | null>(null);
const [viewport, setViewport] = useState({ scale: 1.0, offset: { x: 0, y: 0 } });
const [currentLayer, setCurrentLayer] = useState<TerrainLayer>('gaussian');
const [survivalTab, setSurvivalTab] = useState<'default' | 'high' | 'low'>('default');
const [terrainGain, setTerrainGain] = useState(1.5);
const [dragging, setDragging] = useState(false);
const [lastMouse, setLastMouse] = useState<{x:number, y:number} | null>(null);
const { positionsById } = useMemo(() => computeForcePositions(targets, 800, 600), [targets]);
const mappedTargets = useMemo(() => {
return targets.map((t) => {
const pos = positionsById.get(t.id);
const x = pos?.x ?? 400, y = pos?.y ?? 300;
let value = 0.45 * (t.geneticScore || 0) + 0.25 * (t.combinedExpression || 0) + 0.30 * (t.targetScore || 0);
let status: 'up' | 'down' | 'neutral' = 'neutral';
if (mode === 'survival' && survivalMetrics && survivalMetrics[t.symbol]) {
const met = survivalMetrics[t.symbol];
if (survivalTab === 'high') { value = met.highDiff; status = met.highStatus; }
else if (survivalTab === 'low') { value = met.lowDiff; status = met.lowStatus; }
}
return { ...t, x, y, value, status };
});
}, [targets, positionsById, mode, survivalMetrics, survivalTab]);
const initShader = (gl: WebGLRenderingContext, vs: string, fs: string) => {
const vShader = gl.createShader(gl.VERTEX_SHADER)!; gl.shaderSource(vShader, vs); gl.compileShader(vShader);
const fShader = gl.createShader(gl.FRAGMENT_SHADER)!; gl.shaderSource(fShader, fs); gl.compileShader(fShader);
const prog = gl.createProgram()!; gl.attachShader(prog, vShader); gl.attachShader(prog, fShader); gl.linkProgram(prog);
return prog;
};
const draw = useCallback(() => {
const gl = glRef.current; if (!gl || !glCanvasRef.current) return;
if (!shadersRef.current[currentLayer]) {
let fsSource = terrainFragmentShader;
if (currentLayer === 'discrete') fsSource = contourFragmentShader;
else if (currentLayer === 'water') fsSource = peaksFragmentShader;
else if (currentLayer === 'sky') fsSource = valleyFragmentShader;
shadersRef.current[currentLayer] = initShader(gl, vertexShaderSource, fsSource);
}
const prog = shadersRef.current[currentLayer]; gl.useProgram(prog);
if (!pointsTexRef.current) pointsTexRef.current = gl.createTexture();
const pointsData = new Float32Array(MAX_WebGL_POINTS * 4), valuesData = new Float32Array(MAX_WebGL_POINTS * 4);
const count = Math.min(mappedTargets.length, MAX_WebGL_POINTS);
mappedTargets.slice(0, count).forEach((t, i) => { pointsData[i*4] = t.x!; pointsData[i*4+1] = t.y!; valuesData[i*4] = t.value! * terrainGain; });
gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, pointsTexRef.current);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, MAX_WebGL_POINTS, 1, 0, gl.RGBA, gl.FLOAT, pointsData);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
if (!valuesTexRef.current) valuesTexRef.current = gl.createTexture();
gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, valuesTexRef.current);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, MAX_WebGL_POINTS, 1, 0, gl.RGBA, gl.FLOAT, valuesData);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.uniform1i(gl.getUniformLocation(prog, "pointsTexture"), 0); gl.uniform1i(gl.getUniformLocation(prog, "valuesTexture"), 1);
gl.uniform1i(gl.getUniformLocation(prog, "pointCount"), count); gl.uniform1f(gl.getUniformLocation(prog, "sigma"), getSigmaForZoom(viewport.scale));
gl.uniform2f(gl.getUniformLocation(prog, "resolution"), 800, 600); gl.uniform2f(gl.getUniformLocation(prog, "offset"), viewport.offset.x, viewport.offset.y);
gl.uniform1f(gl.getUniformLocation(prog, "scale"), viewport.scale);
let rMode = (mode === 'survival' && survivalTab !== 'default') ? 1 : 0;
gl.uniform1i(gl.getUniformLocation(prog, "renderMode"), rMode);
if (currentLayer === 'discrete') { gl.uniform1f(gl.getUniformLocation(prog, "lineThickness"), 0.015); gl.uniform1f(gl.getUniformLocation(prog, "isolineSpacing"), 0.25); }
if (!bufferRef.current) { bufferRef.current = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, bufferRef.current); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW); } else gl.bindBuffer(gl.ARRAY_BUFFER, bufferRef.current);
const posAttrib = gl.getAttribLocation(prog, "position"); gl.enableVertexAttribArray(posAttrib); gl.vertexAttribPointer(posAttrib, 2, gl.FLOAT, false, 0, 0);
gl.viewport(0, 0, 800, 600); gl.clearColor(0,0,0,0); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
const ctx = overlayCanvasRef.current?.getContext('2d');
if (ctx) {
ctx.clearRect(0, 0, 800, 600); ctx.save(); ctx.setTransform(viewport.scale, 0, 0, viewport.scale, viewport.offset.x, viewport.offset.y);
mappedTargets.forEach(t => {
const isSelected = t.id === selectedId;
if (isSelected) {
ctx.beginPath(); ctx.arc(t.x!, t.y!, 8 / viewport.scale, 0, Math.PI * 2); ctx.fillStyle = 'rgba(59, 130, 246, 0.25)'; ctx.fill();
ctx.beginPath(); ctx.arc(t.x!, t.y!, 5.5 / viewport.scale, 0, Math.PI * 2); ctx.strokeStyle = '#3b82f6'; ctx.lineWidth = 1.5 / viewport.scale; ctx.stroke();
}
let pointColor = isSelected ? '#3b82f6' : (theme === 'dark' ? '#475569' : '#94a3b8');
let finalRadius = (isSelected ? 5 : 2.5) / viewport.scale;
let strokeColor: string | null = null;
let glowColor: string | null = null;
if (mode === 'survival' && survivalTab !== 'default') {
// Gene plots are forced to grey as requested
pointColor = theme === 'dark' ? '#6b7280' : '#9ca3af';
if (t.status === 'up' || t.status === 'down') {
finalRadius *= 1.2;
}
strokeColor = theme === 'dark' ? '#111111' : '#ffffff';
glowColor = null;
} else if (!isSelected) {
const brightness = Math.min(1, Math.abs(t.value) || 0);
pointColor = theme === 'dark' ? `rgba(${140 + brightness * 80}, ${140 + brightness * 80}, ${140 + brightness * 80}, ${0.45 + brightness * 0.45})` : `rgba(${60 - brightness * 30}, ${60 - brightness * 30}, ${60 - brightness * 30}, ${0.55 + brightness * 0.4})`;
}
if (glowColor) { ctx.shadowBlur = 10 / viewport.scale; ctx.shadowColor = glowColor; }
ctx.beginPath(); ctx.arc(t.x!, t.y!, finalRadius, 0, Math.PI * 2); ctx.fillStyle = pointColor; ctx.fill();
if (strokeColor) { ctx.strokeStyle = strokeColor; ctx.lineWidth = 1.2 / viewport.scale; ctx.stroke(); }
ctx.shadowBlur = 0;
if (viewport.scale > 1.2) { ctx.font = `bold ${10 / viewport.scale}px Inter`; ctx.fillStyle = theme === 'dark' ? '#f5f5f5' : '#1e293b'; ctx.textAlign = 'center'; ctx.fillText(t.symbol, t.x!, t.y! + (finalRadius + 8 / viewport.scale)); }
});
ctx.restore();
}
}, [mappedTargets, viewport, currentLayer, terrainGain, selectedId, theme, mode, survivalTab]);
useEffect(() => {
const canvas = glCanvasRef.current; if (canvas) { glRef.current = canvas.getContext('webgl', { preserveDrawingBuffer: true, antialias: true }); glRef.current?.getExtension('OES_texture_float'); }
return () => { const gl = glRef.current; if (gl) { if (pointsTexRef.current) gl.deleteTexture(pointsTexRef.current); if (valuesTexRef.current) gl.deleteTexture(valuesTexRef.current); if (bufferRef.current) gl.deleteBuffer(bufferRef.current); Object.values(shadersRef.current).forEach(p => gl.deleteProgram(p)); } };
}, []);
useEffect(() => { let frameId: number; const loop = () => { draw(); frameId = requestAnimationFrame(loop); }; frameId = requestAnimationFrame(loop); return () => cancelAnimationFrame(frameId); }, [draw]);
return (
<div className={`relative w-full h-full rounded-xl overflow-hidden border flex flex-col ${theme === 'dark' ? 'bg-[#0a0a0a] border-neutral-800' : (survivalTab !== 'default' ? 'bg-[#E9FBF6]' : 'bg-white') + ' border-neutral-200 shadow-sm'}`}>
{mode === 'survival' && (
<div className={`px-4 py-2 flex items-center justify-between border-b ${theme === 'dark' ? 'bg-[#0d0d0d] border-neutral-800' : 'bg-neutral-50 border-neutral-100'}`}>
<div className="flex items-center gap-1">
<button onClick={() => setSurvivalTab('default')} className={`px-4 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${survivalTab === 'default' ? 'bg-blue-500 text-white shadow-sm' : 'text-neutral-500 hover:bg-neutral-200 dark:hover:bg-neutral-800'}`}>Default Terrain</button>
<button onClick={() => setSurvivalTab('high')} className={`px-4 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${survivalTab === 'high' ? 'bg-[#EB4236] text-white shadow-sm' : 'text-neutral-500 hover:bg-neutral-200 dark:hover:bg-neutral-800'}`}>High Survival (Survivors)</button>
<button onClick={() => setSurvivalTab('low')} className={`px-4 py-1.5 rounded-md text-[10px] font-bold uppercase transition-all ${survivalTab === 'low' ? 'bg-[#4285F5] text-white shadow-sm' : 'text-neutral-500 hover:bg-neutral-200 dark:hover:bg-neutral-800'}`}>Low Survival (Non-Survivors)</button>
</div>
</div>
)}
<div className="flex-1 relative">
<canvas ref={glCanvasRef} width={800} height={600} className="absolute inset-0 w-full h-full" />
<canvas ref={overlayCanvasRef} width={800} height={600} className="absolute inset-0 w-full h-full cursor-default" onMouseDown={e => { setDragging(true); setLastMouse({ x: e.clientX, y: e.clientY }); const rect = overlayCanvasRef.current!.getBoundingClientRect(); const x = (e.clientX - rect.left - viewport.offset.x) / viewport.scale, y = (e.clientY - rect.top - viewport.offset.y) / viewport.scale; const hit = mappedTargets.find(t => isPointInCircle(x, y, t.x!, t.y!, 10 / viewport.scale)); if (hit) onSelect(hit); }} onMouseMove={e => { if (dragging && lastMouse) { setViewport(prev => ({ ...prev, offset: { x: prev.offset.x + (e.clientX - lastMouse.x), y: prev.offset.y + (e.clientY - lastMouse.y) } })); setLastMouse({ x: e.clientX, y: e.clientY }); } }} onMouseUp={() => setDragging(false)} onWheel={e => setViewport(prev => ({ ...prev, scale: Math.max(0.5, Math.min(6, prev.scale * (e.deltaY > 0 ? 0.95 : 1.05))) }))} />
<div className="absolute top-6 left-6 flex flex-col gap-3">
<div className={`p-1 rounded-lg border flex flex-col gap-1 shadow-sm ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-200'}`}>{[ { id: 'gaussian', icon: Globe2, name: 'Evidence Intensity' }, { id: 'discrete', icon: Layers, name: 'Confidence Contours' }, { id: 'water', icon: FlaskConical, name: 'Drugability Peaks' }, { id: 'sky', icon: Microscope, name: 'Genetic Valleys' } ].map(l => (<button key={l.id} title={l.name} onClick={() => setCurrentLayer(l.id as TerrainLayer)} className={`p-2 rounded-md transition-colors ${currentLayer === l.id ? 'bg-blue-500 text-white' : 'text-neutral-500 hover:bg-neutral-100 dark:hover:bg-neutral-800'}`}><l.icon className="w-4 h-4" /></button>))}</div>
<div className={`p-3 rounded-lg border flex flex-col gap-2 shadow-sm ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-200'}`}><div className="flex items-center gap-2"><Volume2 className="w-3.5 h-3.5 text-neutral-400" /><span className="text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase">Amplification</span></div><input type="range" min="0.5" max="3.5" step="0.1" value={terrainGain} onChange={(e) => setTerrainGain(parseFloat(e.target.value))} className="w-20 h-1 bg-neutral-200 rounded-full appearance-none cursor-pointer accent-blue-500"/></div>
</div>
<div className="absolute bottom-6 right-6 flex gap-2"><button onClick={() => setViewport({ scale: 1.0, offset: { x: 0, y: 0 } })} className={`p-2 rounded-md border shadow-sm ${theme === 'dark' ? 'bg-[#171717] border-neutral-800 text-neutral-400' : 'bg-white border-neutral-200 text-neutral-700'} hover:bg-neutral-50 transition-colors`}><RotateCcw className="w-4 h-4" /></button>
<div className="flex rounded-md border shadow-sm overflow-hidden bg-white border-neutral-200 dark:bg-[#171717] dark:border-neutral-800"><button onClick={() => setViewport(v => ({ ...v, scale: Math.min(6, v.scale * 1.2) }))} className="p-2 border-r border-neutral-200 dark:border-neutral-800"><ZoomIn className="w-4 h-4 text-neutral-500" /></button><button onClick={() => setViewport(v => ({ ...v, scale: Math.max(0.5, v.scale * 0.8) }))} className="p-2"><ZoomOut className="w-4 h-4 text-neutral-500" /></button></div>
</div>
</div>
{mode === 'survival' && survivalTab !== 'default' && (
<div className={`p-4 border-t ${theme === 'dark' ? 'bg-[#0d0d0d] border-neutral-800' : 'bg-blue-50 border-neutral-100'}`}>
<div className="flex items-center gap-2 mb-1"><Info className="w-3.5 h-3.5 text-blue-500" /><span className="text-[11px] font-bold text-blue-600 uppercase">Independent Outcome Landscape</span></div>
<p className="text-[11px] text-neutral-600 dark:text-neutral-400 leading-relaxed italic">{survivalTab === 'high' ? "Direct mapping of mean expression for long-surviving patients. Highlights areas of baseline molecular intensity in this cohort." : "Direct mapping of mean expression for short-surviving patients. Highlights areas of baseline molecular intensity in this cohort."}</p>
</div>
)}
</div>
);
};
const RawDataView = ({ targets, theme, cancerType }: { targets: Target[], theme: Theme, cancerType: string }) => {
const [clinicalData, setClinicalData] = useState<ClinicalSample[]>([]);
const [selectedSample, setSelectedSample] = useState<ClinicalSample | null>(null);
const [expressionData, setExpressionData] = useState<ExpressionRow[]>([]);
const [loadingClinical, setLoadingClinical] = useState(false);
const [loadingExpression, setLoadingExpression] = useState(false);
const [showOnlyGetGenes, setShowOnlyGetGenes] = useState(true);
const [offset, setOffset] = useState(0);
const getTargetSymbols = useMemo(() => new Set(targets.map(t => t.symbol)), [targets]);
useEffect(() => {
const fetchClinical = async () => {
setLoadingClinical(true);
const data = await api.getTcgaClinical(cancerType, offset);
// Normalize clinical data keys
const normalized = data.map(item => ({
sampleid: item.SAMPLEID ?? item.sampleid ?? item.SampleID ?? item.sample_id ?? item.sample ?? item.PATIENT_ID ?? item.patient_id,
vital_status: item.VITAL_STATUS ?? item.vital_status ?? item.VitalStatus ?? 'Unknown'
}));
setClinicalData(normalized);
setLoadingClinical(false);
};
fetchClinical();
}, [offset, cancerType]);
const handleSelectSample = async (sample: ClinicalSample) => {
setSelectedSample(sample);
setLoadingExpression(true);
// Use the new expression API format
// Since we need expression for a specific sample, we fetch the target genes
// and filter for this sample. If "Show All" is selected, we are limited by the API
// so we'll primarily support the target list genes.
const genesToFetch = showOnlyGetGenes ? Array.from(getTargetSymbols) : ['TP53', 'BRCA1', 'EGFR', 'MYC', 'PTEN']; // Fallback small list if not filtered
const page = await api.getTcgaExpressionPage(cancerType, genesToFetch, 0);
const sampleRows = page.items.filter(item => {
const sid = (item.SAMPLEID ?? item.sampleid ?? item.SampleID ?? item.sample_id ?? item.sample ?? item.PATIENT_ID ?? item.patient_id)?.toString().trim().toUpperCase();
return sid === sample.sampleid.toString().trim().toUpperCase();
}).map(item => ({
gene_symbol: (item.GENE_SYMBOL ?? item.gene_symbol ?? item.GeneSymbol ?? item.symbol ?? item.Symbol ?? item.gene),
value: (item.EXPRESSION_VALUE ?? item.value ?? item.expression_value ?? item.ExpressionValue ?? item.tpm ?? item.TPM ?? item.exp)
}));
setExpressionData(sampleRows);
setLoadingExpression(false);
};
const filteredExpression = useMemo(() => { if (!showOnlyGetGenes) return expressionData; return expressionData.filter(row => getTargetSymbols.has(row.gene_symbol)); }, [expressionData, getTargetSymbols, showOnlyGetGenes]);
return (
<div className="h-full flex flex-col md:flex-row divide-y md:divide-y-0 md:divide-x divide-neutral-100 dark:divide-neutral-800">
<div className="flex-1 flex flex-col overflow-hidden">
<div className="p-4 border-b border-neutral-100 dark:border-neutral-800 flex items-center justify-between"><div className="flex items-center gap-2"><Stethoscope className="w-4 h-4 text-neutral-500" /><span className="text-[12px] font-semibold text-neutral-700 dark:text-neutral-400">Cohort Explorer</span></div><div className="flex items-center gap-2"><button onClick={() => setOffset(Math.max(0, offset - 10))} disabled={offset === 0} className="p-1 rounded hover:bg-neutral-100 transition-colors"><ChevronLeft className="w-4 h-4" /></button><span className="text-[10px] font-mono text-neutral-600 dark:text-neutral-500">P. {offset/10 + 1}</span><button onClick={() => setOffset(offset + 10)} className="p-1 rounded hover:bg-neutral-100 transition-colors"><ChevronRight className="w-4 h-4" /></button></div></div>
<div className="flex-1 overflow-auto">{loadingClinical ? (<div className="h-full flex items-center justify-center"><Loader2 className="w-6 h-6 animate-spin text-blue-500" /></div>) : (<table className="w-full text-left"><thead className="sticky top-0 bg-neutral-50 dark:bg-neutral-900 border-b border-neutral-100 dark:border-neutral-800 z-10"><tr><th className="p-4 text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase pl-6">Sample ID</th><th className="p-4 text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase">Type</th><th className="p-4 pr-6 text-right text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase">Status</th></tr></thead><tbody className="divide-y divide-neutral-50 dark:divide-neutral-800">{clinicalData.map(sample => (<tr key={sample.sampleid} onClick={() => handleSelectSample(sample)} className={`cursor-pointer transition-colors hover:bg-neutral-50 dark:hover:bg-neutral-800/50 ${selectedSample?.sampleid === sample.sampleid ? 'bg-blue-50/50 dark:bg-blue-900/10' : ''}`}><td className="p-4 pl-6 font-mono text-[11px] text-blue-600 dark:text-blue-400">{sample.sampleid}</td><td className="p-4 text-[11px] text-neutral-700 dark:text-neutral-400">{sample.vital_status === 'Alive' ? 'Alive' : 'Deceased'}</td><td className={`p-4 pr-6 text-right text-[11px] font-medium ${sample.vital_status === 'Alive' ? 'text-[#EB4236]' : 'text-[#4285F5]'}`}>{sample.vital_status}</td></tr>))}</tbody></table>)}</div>
</div>
<div className="flex-1 flex flex-col overflow-hidden">
<div className="p-4 border-b border-neutral-100 dark:border-neutral-800 flex items-center justify-between"><div className="flex items-center gap-2"><Activity className="w-4 h-4 text-neutral-500" /><span className="text-[12px] font-semibold text-neutral-700 dark:text-neutral-400">Sample Expression</span></div><button onClick={() => setShowOnlyGetGenes(!showOnlyGetGenes)} className={`text-[10px] font-bold px-3 py-1 rounded border transition-colors ${showOnlyGetGenes ? 'bg-blue-500 text-white' : 'text-neutral-500'}`}>{showOnlyGetGenes ? 'FILTERED' : 'ALL'}</button></div>
<div className="flex-1 overflow-auto">{!selectedSample ? (<div className="h-full flex flex-col items-center justify-center p-12 text-center text-neutral-400"><DatabaseZap className="w-8 h-8 mb-4 opacity-10" /><p className="text-sm font-medium">Select a patient sample</p></div>) : loadingExpression ? (<div className="h-full flex items-center justify-center"><Loader2 className="w-6 h-6 animate-spin text-blue-500" /></div>) : (<table className="w-full text-left"><thead className="sticky top-0 bg-neutral-50 dark:bg-neutral-900 border-b border-neutral-100 dark:border-neutral-800 z-10"><tr><th className="p-4 text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase pl-6">Gene</th><th className="p-4 text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase text-center">In List</th><th className="p-4 pr-6 text-right text-[10px] font-bold text-neutral-600 dark:text-neutral-500 uppercase">TPM Value</th></tr></thead><tbody className="divide-y divide-neutral-50 dark:divide-neutral-800">{filteredExpression.map(row => { const isGetGene = getTargetSymbols.has(row.gene_symbol); return (<tr key={row.gene_symbol} className={isGetGene ? 'bg-blue-50/20 dark:bg-blue-900/5' : ''}><td className={`p-4 pl-6 font-semibold text-[11px] ${isGetGene ? 'text-blue-600 dark:text-blue-400' : 'text-neutral-600 dark:text-neutral-300'}`}>{row.gene_symbol}</td><td className="p-4 text-center">{isGetGene && <CheckCircle2 className="w-3.5 h-3.5 text-emerald-500 mx-auto" />}</td><td className="p-4 pr-6 text-right font-mono text-[11px] text-neutral-600 dark:text-neutral-500">{parseFloat(row.value).toFixed(4)}</td></tr>); })}</tbody></table>)}</div>
</div>
</div>
);
};
const DrugLandscape = ({
targetId,
symbol,
theme,
currentStatus,
onToggle,
onSave
}: {
targetId: string,
symbol: string,
theme: Theme,
currentStatus?: 'useful' | 'not-useful' | 'pinned',
onToggle: (symbol: string, source: string, status: 'useful' | 'not-useful' | 'pinned') => void,
onSave?: () => void
}) => {
const [drugs, setDrugs] = useState<DrugInfo[]>([]); const [loading, setLoading] = useState(false);
useEffect(() => { let active = true; const fetch = async () => { setLoading(true); const res = await api.getTargetDrugs(targetId); if (active) { setDrugs(res); setLoading(false); } }; fetch(); return () => { active = false; }; }, [targetId]);
if (loading) return <div className="flex items-center gap-3 py-4"><Loader2 className="w-4 h-4 animate-spin text-blue-500" /><span className="text-[11px] font-medium text-neutral-500">Mapping clinical pipeline...</span></div>;
if (drugs.length === 0) return null;
return (
<div className="space-y-5">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Pill className="w-4 h-4 text-neutral-500" />
<h4 className="text-[11px] font-bold uppercase text-neutral-600 dark:text-neutral-500">Pipeline Evidence</h4>
</div>
<UsefulnessControls
symbol={symbol}
source="clinical"
currentStatus={currentStatus}
onToggle={onToggle}
onSave={onSave}
theme={theme}
/>
</div>
<div className="space-y-3">
{drugs.slice(0, 4).map(d => (
<div key={d.id} className={`p-4 rounded-lg border ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-neutral-50 border-neutral-200 shadow-sm'}`}>
<div className="flex items-center justify-between mb-3">
<span className="text-[11px] font-bold text-blue-600 dark:text-blue-500 uppercase">{d.name}</span>
<span className="text-[9px] font-bold text-neutral-500 dark:text-neutral-400 uppercase">PHASE {d.phase}</span>
</div>
<PipelineProgress phase={d.phase} />
<p className={`text-[11px] leading-relaxed italic mt-3 ${theme === 'dark' ? 'text-neutral-400' : 'text-neutral-700'}`}>{d.mechanism}</p>
</div>
))}
</div>
</div>
);
};
const LiteratureStats = ({
symbol,
diseaseName,
theme,
currentStatus,
onToggle,
onSave
}: {
symbol: string,
diseaseName: string,
theme: Theme,
currentStatus?: 'useful' | 'not-useful' | 'pinned',
onToggle: (symbol: string, source: string, status: 'useful' | 'not-useful' | 'pinned') => void,
onSave?: () => void
}) => {
const [stats, setStats] = useState<PubMedStats | null>(null); const [loading, setLoading] = useState(false);
useEffect(() => { let active = true; const fetch = async () => { setLoading(true); const res = await api.getPubMedStats(symbol, diseaseName); if (active) { setStats(res); setLoading(false); } }; fetch(); return () => { active = false; }; }, [symbol, diseaseName]);
if (loading) return <div className="flex items-center gap-3 py-6"><Loader2 className="w-4 h-4 animate-spin text-blue-500" /><span className="text-[11px] font-medium text-neutral-500">Retrieving PubMed analytics...</span></div>;
if (!stats) return null;
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<BookOpen className="w-4 h-4 text-neutral-500" />
<h4 className="text-[11px] font-bold uppercase text-neutral-600 dark:text-neutral-500">Clinical Publications</h4>
</div>
<UsefulnessControls
symbol={symbol}
source="literature"
currentStatus={currentStatus}
onToggle={onToggle}
onSave={onSave}
theme={theme}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className={`p-4 rounded-lg border ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-neutral-50 border-neutral-200 shadow-sm'}`}>
<div className="text-[9px] font-bold text-neutral-500 dark:text-neutral-400 uppercase mb-1">Literature Count</div>
<div className={`text-lg font-bold ${theme === 'dark' ? 'text-white' : 'text-neutral-900'}`}>{stats.total.toLocaleString()}</div>
</div>
<a href={stats.primarySearchLink} target="_blank" rel="noopener noreferrer" className={`p-4 rounded-lg border block hover:bg-blue-100/50 transition-colors ${theme === 'dark' ? 'bg-blue-900/5 border-blue-500/20' : 'bg-blue-50 border-blue-100 shadow-sm'}`}>
<div className="flex items-center justify-between mb-1">
<div className="text-[9px] font-bold text-blue-600 dark:text-blue-500 uppercase">Recent (2024-25)</div>
<ExternalLink className="w-2.5 h-2.5 text-blue-400" />
</div>
<div className="text-lg font-bold text-blue-700 dark:text-blue-400">{stats.recent.toLocaleString()}</div>
</a>
</div>
<div className={`p-4 rounded-lg border ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-neutral-50 border-neutral-200 shadow-sm'}`}>
<div className="flex items-center justify-between mb-2">
<span className="text-[9px] font-bold uppercase text-neutral-500 dark:text-neutral-400">Velocity (2y)</span>
<Activity className="w-3 h-3 text-blue-500" />
</div>
<PublicationSparkline recent={stats.recent} total={stats.total} theme={theme} />
</div>
<div className="space-y-3">
{stats.topPapers.map(p => (
<a key={p.id} href={`https://pubmed.ncbi.nlm.nih.gov/${p.id}/`} target="_blank" rel="noopener noreferrer" className={`block p-4 rounded-lg border transition-all hover:bg-neutral-100 dark:hover:bg-neutral-800/50 ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-200 shadow-sm'}`}>
<p className={`text-[11px] font-medium leading-relaxed mb-2 line-clamp-2 ${theme === 'dark' ? 'text-neutral-300' : 'text-neutral-800'}`}>{p.title}</p>
<div className="text-[9px] font-mono text-neutral-500 uppercase tracking-wider">PMID {p.id}</div>
</a>
))}
</div>
</div>
);
};
const UsefulnessControls = ({
symbol,
source,
currentStatus,
onToggle,
onSave,
theme
}: {
symbol: string;
source: string;
currentStatus?: 'useful' | 'not-useful' | 'pinned';
onToggle: (symbol: string, source: string, status: 'useful' | 'not-useful' | 'pinned') => void;
onSave?: () => void;
theme: Theme;
}) => {
const isPinned = currentStatus === 'pinned';
return (
<div className="flex items-center gap-1 mt-2">
<button
onClick={(e) => { e.stopPropagation(); onToggle(symbol, source, 'pinned'); }}
className={`p-1.5 rounded-md transition-all group ${
isPinned
? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400'
: 'hover:bg-neutral-100 dark:hover:bg-neutral-800 text-neutral-400'
}`}
title="Pin to Top"
>
<Pin className={`w-3.5 h-3.5 ${isPinned ? 'fill-current' : 'group-hover:text-blue-500'}`} />
</button>
<button
onClick={(e) => {
e.stopPropagation();
if (onSave) {
onSave();
} else if (!isPinned) {
onToggle(symbol, source, 'not-useful');
}
}}
disabled={isPinned}
className={`p-1.5 rounded-md transition-all group relative ${
currentStatus === 'not-useful'
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400 ring-2 ring-emerald-500/50 shadow-[0_0_10px_rgba(16,185,129,0.5)]'
: isPinned ? 'opacity-20 cursor-not-allowed text-neutral-300' : 'hover:bg-neutral-100 dark:hover:bg-neutral-800 text-neutral-400'
}`}
title={isPinned ? "Cannot save pinned information" : "Save to Report"}
>
<Save className={`w-3.5 h-3.5 ${currentStatus === 'not-useful' ? 'fill-current' : 'group-hover:text-emerald-500'}`} />
</button>
</div>
);
};
// =============================================================================
// Navigation Components
// =============================================================================
const Breadcrumbs = ({
activeDisease,
focusSymbol,
focusSubPage,
onNavigate,
theme
}: {
activeDisease?: DiseaseInfo | null;
focusSymbol?: string | null;
focusSubPage?: 'main' | 'literature' | 'clinical' | null;
onNavigate: (level: 'home' | 'disease' | 'target' | 'subpage') => void;
theme: Theme;
}) => {
return (
<nav className="flex items-center gap-2 mb-5 text-[10px] font-bold uppercase tracking-widest overflow-x-auto custom-scrollbar-x pb-1">
<button
onClick={() => onNavigate('home')}
className={`flex items-center gap-1.5 transition-all px-2 py-1 rounded-md hover:bg-neutral-100 dark:hover:bg-neutral-800 whitespace-nowrap ${!activeDisease ? 'text-blue-600 bg-blue-50/50 dark:bg-blue-900/10' : 'text-neutral-400 hover:text-blue-500'}`}
>
<Home className="w-3.5 h-3.5" />
Home
</button>
{activeDisease && (
<>
<ChevronRight className="w-3 h-3 text-neutral-300 dark:text-neutral-700 shrink-0" />
<button
onClick={() => onNavigate('disease')}
className={`flex items-center gap-1.5 transition-all px-2 py-1 rounded-md hover:bg-neutral-100 dark:hover:bg-neutral-800 whitespace-nowrap ${activeDisease && !focusSymbol ? 'text-blue-600 bg-blue-50/50 dark:bg-blue-900/10' : 'text-neutral-400 hover:text-blue-500'}`}
>
<FlaskConical className="w-3.5 h-3.5" />
{activeDisease.name}
</button>
</>
)}
{focusSymbol && (
<>
<ChevronRight className="w-3 h-3 text-neutral-300 dark:text-neutral-700 shrink-0" />
<button
onClick={() => onNavigate('target')}
className={`flex items-center gap-1.5 transition-all px-2 py-1 rounded-md hover:bg-neutral-100 dark:hover:bg-neutral-800 whitespace-nowrap ${focusSymbol && focusSubPage === 'main' ? 'text-blue-600 bg-blue-50/50 dark:bg-blue-900/10' : 'text-neutral-400 hover:text-blue-500'}`}
>
<Atom className="w-3.5 h-3.5" />
{focusSymbol}
</button>
</>
)}
{focusSymbol && focusSubPage === 'literature' && (
<>
<ChevronRight className="w-3 h-3 text-neutral-300 dark:text-neutral-700 shrink-0" />
<div className="flex items-center gap-1.5 text-blue-600 bg-blue-50/50 dark:bg-blue-900/10 px-2 py-1 rounded-md whitespace-nowrap">
<BookOpen className="w-3.5 h-3.5" />
Literature Intelligence
</div>
</>
)}
</nav>
);
};
const TargetDetailView = ({
target,
theme,
diseaseName,
subPage = 'main',
onToggleUsefulness,
onNavigateSubPage,
onSave,
onBack
}: {
target: Target;
theme: Theme;
diseaseName: string;
subPage?: 'main' | 'literature' | 'clinical';
onToggleUsefulness: (symbol: string, source: string, status: 'useful' | 'not-useful' | 'pinned' | null) => void;
onNavigateSubPage: (page: 'main' | 'literature' | 'clinical') => void;
onSave?: () => void;
onBack: () => void;
}) => {
if (subPage === 'literature') {
return (
<div className="h-full flex flex-col overflow-hidden animate-in fade-in slide-in-from-right-4 duration-500">
<div className={`p-6 border-b flex items-center justify-between ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-100'}`}>
<div className="flex items-center gap-4">
<button
onClick={() => onNavigateSubPage('main')}
className="p-2 rounded-full hover:bg-neutral-100 dark:hover:bg-neutral-800 transition-colors"
>
<ChevronLeft className="w-5 h-5 text-neutral-400" />
</button>
<div className="space-y-1">
<h3 className="text-2xl font-black text-purple-600 dark:text-purple-400 tracking-tighter flex items-center gap-2">
<BookOpen className="w-6 h-6" /> Literature Intelligence: {target.symbol}
</h3>
<p className="text-[10px] font-bold uppercase text-neutral-400 tracking-widest">Scientific publication trends and evidence mapping</p>
</div>
</div>
</div>
<div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
<div className="max-w-4xl mx-auto space-y-10">
{target.drillDown ? (
<>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className={`p-6 rounded-2xl border ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-200 shadow-sm'}`}>
<span className="text-[10px] font-bold text-neutral-400 uppercase block mb-1">Literature Count</span>
<span className="text-3xl font-black text-purple-600">{target.drillDown.total_signals || 0}</span>
</div>
<div className={`p-6 rounded-2xl border ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-200 shadow-sm'}`}>
<span className="text-[10px] font-bold text-neutral-400 uppercase block mb-1">Recent (2024-25)</span>
<span className="text-3xl font-black text-purple-600">{target.drillDown.recent_signals || 0}</span>
</div>
<div className={`p-6 rounded-2xl border ${theme === 'dark' ? 'bg-[#171717] border-neutral-800' : 'bg-white border-neutral-200 shadow-sm'}`}>
<span className="text-[10px] font-bold text-neutral-400 uppercase block mb-1">Velocity (2y)</span>
<span className="text-2xl font-black text-purple-600">{target.drillDown.signal_velocity || '0%'}</span>
</div>
</div>
<div className="space-y-6">
<h4 className="text-[12px] font-bold uppercase text-neutral-500 tracking-widest border-b pb-2">Publication Intelligence</h4>
<LiteratureStats
symbol={target.symbol}
diseaseName={diseaseName}
theme={theme}
currentStatus={target.usefulness?.['literature']}
onToggle={onToggleUsefulness}
onSave={onSave}
/>
</div>
<div className="pt-10 space-y-4">
<h4 className="text-[12px] font-bold uppercase text-neutral-500 tracking-widest">Global Evidence Repositories</h4>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<a
href={`https://pubmed.ncbi.nlm.nih.gov/?term=${encodeURIComponent(target.symbol)}+${encodeURIComponent(diseaseName)}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-between p-5 rounded-2xl border border-neutral-200 dark:border-neutral-800 hover:bg-purple-50 dark:hover:bg-purple-900/10 transition-all group"
>
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-purple-100 dark:bg-purple-900/30 text-purple-600"><FileText className="w-5 h-5" /></div>
<div className="text-left">
<span className="text-[11px] font-black text-neutral-800 dark:text-neutral-200 block">PubMed / MEDLINE</span>
<span className="text-[9px] font-bold text-neutral-400 uppercase">NIH National Library</span>
</div>
</div>
<ExternalLink className="w-4 h-4 text-neutral-300 group-hover:text-purple-500 transition-colors" />
</a>
<a
href={`https://europepmc.org/search?query=${encodeURIComponent(target.symbol)}+AND+${encodeURIComponent(diseaseName)}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-between p-5 rounded-2xl border border-neutral-200 dark:border-neutral-800 hover:bg-indigo-50 dark:hover:bg-indigo-900/10 transition-all group"
>
<div className="flex items-center gap-3">
<div className="p-2 rounded-xl bg-indigo-100 dark:bg-indigo-900/30 text-indigo-600"><Globe2 className="w-5 h-5" /></div>
<div className="text-left">
<span className="text-[11px] font-black text-neutral-800 dark:text-neutral-200 block">Europe PMC</span>
<span className="text-[9px] font-bold text-neutral-400 uppercase">EMBL-EBI Open Access</span>
</div>
</div>
<ExternalLink className="w-4 h-4 text-neutral-300 group-hover:text-indigo-500 transition-colors" />
</a>
</div>
</div>