-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1962 lines (1937 loc) · 123 KB
/
Copy pathapp.js
File metadata and controls
1962 lines (1937 loc) · 123 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
// RNAnix v2 — chat shell around a REAL Mol* viewer + real client-side data tools, wired to the
// real rna-atlas-inference backend (same bridge Lambda / Step Functions pipeline as v1's
// /inference page) when window.INFER_API is set. With INFER_API unset this still runs as a full
// offline mockup: predictions fall back to a staged demo instead of a network call, exactly the
// same "demo mode" convention as frontend/inference.js in the backend repo.
(function () {
var $ = function (id) { return document.getElementById(id); };
if (!$('chatBody')) return; // login.html doesn't need any of this
// ================= real backend wiring =================
// Set before this file loads, e.g. <script>window.INFER_API = "https://xyz.execute-api...";
// window.INFER_TOKEN = "...";</script> — same contract as frontend/inference.js in
// rna-atlas-inference. Empty INFER_API => every backend call below is skipped in favor of the
// existing staged/simulated flow.
var API = (window.INFER_API || '').replace(/\/$/, '');
function tok() { return window.INFER_TOKEN || ''; }
function fmtOf(text) { return (text.startsWith('data_') || text.includes('_atom_site')) ? 'cif' : 'pdb'; }
// ================= small utilities =================
var _enc = function (s) { return new TextEncoder().encode(s); };
function toast(msg) {
var t = $('toast');
if (!t) { t = document.createElement('div'); t.id = 'toast'; t.className = 'toast'; document.body.appendChild(t); }
t.textContent = msg; t.classList.add('show');
clearTimeout(toast._h); toast._h = setTimeout(function () { t.classList.remove('show'); }, 2800);
}
var _CRCT = null;
function crc32(u8) {
if (!_CRCT) { _CRCT = []; for (var n = 0; n < 256; n++) { var c = n; for (var k = 0; k < 8; k++) c = c & 1 ? 0xEDB88320 ^ (c >>> 1) : c >>> 1; _CRCT[n] = c >>> 0; } }
var crc = 0xFFFFFFFF; for (var i = 0; i < u8.length; i++) crc = _CRCT[(crc ^ u8[i]) & 0xFF] ^ (crc >>> 8);
return (crc ^ 0xFFFFFFFF) >>> 0;
}
function zipStore(files) {
var parts = [], central = [], off = 0;
files.forEach(function (f) {
var nb = _enc(f.name), d = f.data, crc = crc32(d);
var lh = new Uint8Array(30 + nb.length), lv = new DataView(lh.buffer);
lv.setUint32(0, 0x04034b50, true); lv.setUint16(4, 20, true);
lv.setUint32(14, crc, true); lv.setUint32(18, d.length, true); lv.setUint32(22, d.length, true);
lv.setUint16(26, nb.length, true); lh.set(nb, 30); parts.push(lh, d);
var ch = new Uint8Array(46 + nb.length), cv = new DataView(ch.buffer);
cv.setUint32(0, 0x02014b50, true); cv.setUint16(4, 20, true); cv.setUint16(6, 20, true);
cv.setUint32(16, crc, true); cv.setUint32(20, d.length, true); cv.setUint32(24, d.length, true);
cv.setUint16(28, nb.length, true); cv.setUint32(42, off, true); ch.set(nb, 46);
central.push(ch); off += lh.length + d.length;
});
var cs = central.reduce(function (s, c) { return s + c.length; }, 0);
var end = new Uint8Array(22), ev = new DataView(end.buffer);
ev.setUint32(0, 0x06054b50, true); ev.setUint16(8, files.length, true); ev.setUint16(10, files.length, true);
ev.setUint32(12, cs, true); ev.setUint32(16, off, true);
return new Blob(parts.concat(central, [end]), { type: 'application/zip' });
}
function dataURIBytes(uri) { var bin = atob(uri.split(',')[1]), u8 = new Uint8Array(bin.length); for (var i = 0; i < bin.length; i++) u8[i] = bin.charCodeAt(i); return u8; }
function downloadBlob(name, text) {
var a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([text], { type: 'text/plain' })); a.download = name;
document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(a.href); }, 2000);
}
function downloadDataUri(name, uri) { var a = document.createElement('a'); a.href = uri; a.download = name; document.body.appendChild(a); a.click(); a.remove(); }
function downloadZip(name, files) {
var a = document.createElement('a'); a.href = URL.createObjectURL(zipStore(files)); a.download = name;
document.body.appendChild(a); a.click(); a.remove(); setTimeout(function () { URL.revokeObjectURL(a.href); }, 2000);
}
// ================= real Mol* viewer =================
var mstar = null, molstarLoading = null;
var curPdbId = null, curPdbText = null, curSeq = "";
// Which prediction job's result is currently shown as the primary layer -- the job-side
// counterpart to curPdbId, so render() can tell whether switching to a prediction-result
// thread actually needs to reopen its job (see render()'s t.lastJobId branch).
var curJobId = null;
var compHide = { polymer: false, ligand: false, water: false, ion: false };
// Multiple structures can now be co-rendered ("Add to 3D" from Templates) as independent
// layers in the SAME Mol* scene — layers[0] is always the "primary" structure (the one chat
// fetches/predictions load); everything after it is an overlay. curPdbId/curPdbText below stay
// as convenience mirrors of layers[0] so the rest of the file (downloads, SS tab, chat parser)
// doesn't need to know about the layers array at all.
var layers = [], nextLayerId = 1;
var LAYER_COLORS = ['#2fd6a7', '#e8862e', '#4d96ff', '#ef476f', '#6bcb77', '#ffb703'];
function syncPrimaryAliases() {
var L = layers[0];
curPdbId = L ? L.pdbId : null;
curPdbText = L ? L.text : null;
}
var themeChosen = false; // becomes true once the user explicitly picks a Style/Color scheme
var ICON_EYE_ON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7-11-7-11-7z"/><circle cx="12" cy="12" r="3"/></svg>';
var ICON_EYE_OFF = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19c-7 0-11-7-11-7a20.4 20.4 0 0 1 5.06-5.94M9.9 4.24A10.94 10.94 0 0 1 12 4c7 0 11 7 11 7a20.4 20.4 0 0 1-2.68 3.68M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
var ICON_MOON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>';
var ICON_SUN = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>';
var ICON_WRENCH = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px"><path d="M14.7 6.3a4 4 0 0 0-5.4 5.4L2 19l3 3 7.3-7.3a4 4 0 0 0 5.4-5.4l-2.8 2.8-2-2z"/></svg>';
var ICON_SPARKLE = '<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:-1px"><path d="M12 2l1.8 5.2L19 9l-5.2 1.8L12 16l-1.8-5.2L5 9l5.2-1.8z"/></svg>';
var ICON_EXTLINK = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px"><path d="M7 17L17 7"/><path d="M8 7h9v9"/></svg>';
var ICON_WARNING = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px"><path d="M10.3 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.7 3.86a2 2 0 0 0-3.4 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>';
var ICON_PIN = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5"/><path d="M9 3h6l1 6 3 3v2H5v-2l3-3z"/></svg>';
// Backend errors often arrive as "<context>: <raw JSON from the upstream API>" (e.g. Claude's
// {"error":{"message":"..."}}) -- pull out just the human message instead of showing the raw
// blob verbatim in a chat bubble.
function extractErrorMessage(raw) {
if (!raw) return '';
var s = String(raw);
var m = s.match(/\{[\s\S]*\}/);
if (m) {
try {
var j = JSON.parse(m[0]);
var msg = (j.error && (j.error.message || j.error.type)) || j.message;
if (msg) return msg;
} catch (e) { /* not JSON, or not the shape we expect -- fall through */ }
}
return s;
}
var WATER = { HOH: 1, WAT: 1, H2O: 1 };
var IONS = { NA: 1, MG: 1, K: 1, CL: 1, CA: 1, ZN: 1, MN: 1, FE: 1, CU: 1, CO: 1, NI: 1, CD: 1, BR: 1, IOD: 1, CS: 1, LI: 1, SR: 1, BA: 1 };
var NT1 = { A: 'A', C: 'C', G: 'G', U: 'U', T: 'T', DA: 'A', DC: 'C', DG: 'G', DT: 'T' };
var AA1 = { ALA: 'A', ARG: 'R', ASN: 'N', ASP: 'D', CYS: 'C', GLN: 'Q', GLU: 'E', GLY: 'G', HIS: 'H', ILE: 'I', LEU: 'L', LYS: 'K', MET: 'M', PHE: 'F', PRO: 'P', SER: 'S', THR: 'T', TRP: 'W', TYR: 'Y', VAL: 'V' };
function loadMolstarLib() {
if (window.molstar) return Promise.resolve();
if (molstarLoading) return molstarLoading;
molstarLoading = new Promise(function (res, rej) {
var css = document.createElement('link'); css.rel = 'stylesheet'; css.href = 'molstar.css'; document.head.appendChild(css);
var s = document.createElement('script'); s.src = 'molstar.js';
s.onload = function () { res(); }; s.onerror = function () { rej(new Error('molstar.js failed to load')); };
document.head.appendChild(s);
});
return molstarLoading;
}
async function ensureViewer() {
if (mstar) return mstar;
await loadMolstarLib();
mstar = await molstar.Viewer.create($('mstarContainer'), {
layoutIsExpanded: false, layoutShowControls: false, layoutShowSequence: false,
layoutShowLog: false, layoutShowLeftPanel: false,
viewportShowExpand: false, viewportShowSelectionMode: false, viewportShowAnimation: false,
viewportShowControls: false, viewportShowSettings: false, viewportShowTrajectoryControls: false,
});
return mstar;
}
function setViewerMsg(txt) { var el = $('viewerMsg'); if (!el) return; el.textContent = txt || ''; el.style.display = txt ? 'flex' : 'none'; }
async function fetchPdbText(id) {
var r = await fetch('https://files.rcsb.org/download/' + id.toUpperCase() + '.pdb');
if (!r.ok) throw new Error('RCSB returned HTTP ' + r.status);
return r.text();
}
async function fetchCifText(id) {
var r = await fetch('https://files.rcsb.org/download/' + id.toUpperCase() + '.cif');
if (!r.ok) throw new Error('RCSB returned HTTP ' + r.status);
return r.text();
}
function filterPdbText(text, hide) {
return text.split('\n').filter(function (line) {
var rec = line.slice(0, 6);
if (rec !== 'ATOM ' && rec !== 'HETATM') return true;
var resn = line.slice(17, 20).trim().toUpperCase();
if (rec === 'ATOM ') return !hide.polymer;
if (WATER[resn]) return !hide.water;
if (IONS[resn]) return !hide.ion;
return !hide.ligand;
}).join('\n');
}
// One pass over ATOM records: builds per-chain residue order AND each residue's atom
// centroid (for real camera-focus-on-click), keyed together so they can never drift apart.
function parseResidues(text) {
var chains = {}, order = [], acc = {};
text.split('\n').forEach(function (line) {
if (line.slice(0, 6) !== 'ATOM ') return;
var chain = line.slice(21, 22).trim() || 'A';
var resiStr = line.slice(22, 26).trim();
var resn = line.slice(17, 20).trim().toUpperCase();
var x = parseFloat(line.slice(30, 38)), y = parseFloat(line.slice(38, 46)), z = parseFloat(line.slice(46, 54));
var bf = parseFloat(line.slice(60, 66));
if (!isFinite(x) || !isFinite(y) || !isFinite(z)) return;
var key = chain + ':' + resiStr;
if (!acc[key]) {
var isNt = !!NT1[resn], isAa = !isNt && !!AA1[resn];
acc[key] = { code: NT1[resn] || AA1[resn] || 'N', kind: isNt ? 'nt' : (isAa ? 'aa' : 'x'), x: 0, y: 0, z: 0, n: 0, bf: 0, bn: 0 };
if (!chains[chain]) { chains[chain] = []; order.push(chain); }
chains[chain].push(key);
}
var a = acc[key]; a.x += x; a.y += y; a.z += z; a.n++;
if (isFinite(bf)) { a.bf += bf; a.bn++; }
});
// bf ends up as this residue's mean per-atom B-factor -- for a prediction whose pipeline
// writes per-residue pLDDT into that column (confirmed for the reference-stack pipeline this
// deployment routes to), that mean IS the residue's pLDDT; for an experimental PDB entry it's
// the real crystallographic B-factor instead, a different physical quantity on the same
// 0-100-ish numeric scale -- see the isPrediction gate around the confidence-trim command below.
Object.keys(acc).forEach(function (k) { var a = acc[k]; a.x /= a.n; a.y /= a.n; a.z /= a.n; a.bf = a.bn ? a.bf / a.bn : null; });
return { chains: chains, order: order, residues: acc };
}
// mmCIF equivalent of parseResidues -- REAL prediction results from this pipeline come back as
// mmCIF, not legacy PDB (confirmed against actual S3 output), so this is the common case, not
// an edge case: without it, get_structure_data/filter_residues_by_confidence silently had no
// confidence data to work with for almost every real prediction. mmCIF's _atom_site loop is
// whitespace-columnar with a declared header (not PDB's fixed byte-offsets), so column
// positions are read from that header rather than hardcoded, in case a different pipeline
// version orders them differently.
function parseCifResidues(text) {
var lines = text.split('\n'), headers = [], dataStart = -1;
for (var i = 0; i < lines.length; i++) {
var l = lines[i].trim();
if (l.indexOf('_atom_site.') === 0) { headers.push(l.slice('_atom_site.'.length).trim()); continue; }
if (headers.length && l && l !== 'loop_') { dataStart = i; break; }
}
var need = ['group_PDB', 'auth_asym_id', 'auth_seq_id', 'auth_comp_id', 'B_iso_or_equiv', 'Cartn_x', 'Cartn_y', 'Cartn_z'];
var idx = {}; headers.forEach(function (h, i) { idx[h] = i; });
if (dataStart === -1 || need.some(function (k) { return !(k in idx); })) return null;
function tokenize(line) {
var out = [], m, re = /'[^']*'|"[^"]*"|\S+/g;
while ((m = re.exec(line))) out.push(m[0].replace(/^['"]|['"]$/g, ''));
return out;
}
var chains = {}, order = [], acc = {};
for (var j = dataStart; j < lines.length; j++) {
var raw = lines[j].trim();
if (!raw) continue;
if (raw[0] === '_' || raw === 'loop_' || raw === '#') break; // end of this loop's data rows
var t = tokenize(raw);
if (t.length <= idx.B_iso_or_equiv || (t[idx.group_PDB] !== 'ATOM' && t[idx.group_PDB] !== 'HETATM')) continue;
var chain = t[idx.auth_asym_id] || 'A', resiStr = t[idx.auth_seq_id], resn = (t[idx.auth_comp_id] || '').toUpperCase();
var x = parseFloat(t[idx.Cartn_x]), y = parseFloat(t[idx.Cartn_y]), z = parseFloat(t[idx.Cartn_z]), bf = parseFloat(t[idx.B_iso_or_equiv]);
if (!isFinite(x) || !isFinite(y) || !isFinite(z)) continue;
var key = chain + ':' + resiStr;
if (!acc[key]) {
var isNt = !!NT1[resn], isAa = !isNt && !!AA1[resn];
acc[key] = { code: NT1[resn] || AA1[resn] || 'N', kind: isNt ? 'nt' : (isAa ? 'aa' : 'x'), x: 0, y: 0, z: 0, n: 0, bf: 0, bn: 0 };
if (!chains[chain]) { chains[chain] = []; order.push(chain); }
chains[chain].push(key);
}
var a = acc[key]; a.x += x; a.y += y; a.z += z; a.n++;
if (isFinite(bf)) { a.bf += bf; a.bn++; }
}
if (!order.length) return null;
Object.keys(acc).forEach(function (k) { var a = acc[k]; a.x /= a.n; a.y /= a.n; a.z /= a.n; a.bf = a.bn ? a.bf / a.bn : null; });
return { chains: chains, order: order, residues: acc };
}
// Hides residues whose mean per-residue B-factor (pLDDT, for a prediction layer) falls below
// minConf -- separate from filterPdbText's polymer/ligand/water/ion component toggles, and
// applied on top of them in renderLayers.
function filterByConfidence(text, parsed, minConf) {
if (minConf == null || !parsed) return text;
return text.split('\n').filter(function (line) {
if (line.slice(0, 6) !== 'ATOM ') return true;
var chain = line.slice(21, 22).trim() || 'A', resiStr = line.slice(22, 26).trim();
var res = parsed.residues[chain + ':' + resiStr];
return !res || res.bf == null || res.bf >= minConf;
}).join('\n');
}
// mmCIF equivalent of filterByConfidence -- same header-driven column lookup as parseCifResidues.
function filterCifByConfidence(text, parsed, minConf) {
if (minConf == null || !parsed) return text;
var lines = text.split('\n'), headers = [], dataStart = -1;
for (var i = 0; i < lines.length; i++) {
var l = lines[i].trim();
if (l.indexOf('_atom_site.') === 0) { headers.push(l.slice('_atom_site.'.length).trim()); continue; }
if (headers.length && l && l !== 'loop_') { dataStart = i; break; }
}
var idx = {}; headers.forEach(function (h, i) { idx[h] = i; });
if (dataStart === -1 || !('group_PDB' in idx) || !('auth_asym_id' in idx) || !('auth_seq_id' in idx)) return text;
function tokenize(line) {
var out = [], m, re = /'[^']*'|"[^"]*"|\S+/g;
while ((m = re.exec(line))) out.push(m[0].replace(/^['"]|['"]$/g, ''));
return out;
}
var dataEnd = lines.length;
for (var j = dataStart; j < lines.length; j++) {
var raw = lines[j].trim();
if (raw && (raw[0] === '_' || raw === 'loop_' || raw === '#')) { dataEnd = j; break; }
}
var out = lines.slice(0, dataStart);
for (var k = dataStart; k < dataEnd; k++) {
var rawLine = lines[k], trimmed = rawLine.trim();
if (!trimmed) { out.push(rawLine); continue; }
var t = tokenize(trimmed);
if (t[idx.group_PDB] !== 'ATOM' && t[idx.group_PDB] !== 'HETATM') { out.push(rawLine); continue; }
var key = (t[idx.auth_asym_id] || 'A') + ':' + t[idx.auth_seq_id];
var res = parsed.residues[key];
if (!res || res.bf == null || res.bf >= minConf) out.push(rawLine);
}
return out.concat(lines.slice(dataEnd)).join('\n');
}
function tryFocusResidue(res) {
try {
var cam = mstar && mstar.plugin && mstar.plugin.canvas3d && mstar.plugin.canvas3d.camera;
if (!cam || !res) return false;
cam.setState({ target: [res.x, res.y, res.z], radius: 12 }, 260);
return true;
} catch (e) { return false; }
}
var confThreshold = null; // pLDDT/B-factor cutoff from a "trim below X%" chat command, or null
var curStyle = 'Cartoon', curColor = 'Chain';
function setStyleBtn(name) {
curStyle = name;
document.querySelectorAll('#styleGroup .seg-btn').forEach(function (b) { b.classList.toggle('active', b.dataset.style === name); });
}
function setColorBtn(name) {
curColor = name;
document.querySelectorAll('#colorGroup .seg-btn').forEach(function (b) { b.classList.toggle('active', b.dataset.color === name); });
}
document.querySelectorAll('#styleGroup .seg-btn').forEach(function (b) { b.onclick = function () { setStyleBtn(b.dataset.style); themeChosen = true; if (curPdbText) renderLayers(true); }; });
document.querySelectorAll('#colorGroup .seg-btn').forEach(function (b) { b.onclick = function () { setColorBtn(b.dataset.color); themeChosen = true; if (curPdbText) renderLayers(true); }; });
var STYLE_MAP = { 'Cartoon': 'cartoon', 'Surface': 'molecular-surface', 'Ball & stick': 'ball-and-stick' };
var COLOR_MAP = { Chain: 'chain-id', Rainbow: 'polymer-index', pLDDT: 'uncertainty', Element: 'element-symbol' };
// Rank scrubber: layers[0].ranks (set by addPredictionLayer when /status handed back more than
// one finalize_inference.py pick) is the full ordered list of per-rank structure texts;
// rankIndex is which one layers[0].text currently shows. Only meaningful for the primary
// (prediction) layer -- overlay layers from "Add to 3D" never carry .ranks.
function renderRankScrubber() {
var el = $('rankScrubber'); if (!el) return;
var L = layers[0];
if (!L || !L.ranks || L.ranks.length <= 1) { el.hidden = true; return; }
el.hidden = false;
$('rankLabel').textContent = 'Rank ' + (L.rankIndex + 1) + ' of ' + L.ranks.length;
var overlaid = layers.length > 1;
var btn = $('rankOverlayBtn');
btn.textContent = overlaid ? 'Show 1 only' : 'Overlay all';
btn.classList.toggle('active', overlaid);
// Scrubbing the primary layer while other ranks are already overlaid would swap which rank
// the primary shows out from under an already-visible "Rank N" overlay layer of the same rank
// -- hide prev/next rather than let that duplicate/orphan a layer; the Layers panel already
// covers per-rank show/hide/remove once everything's overlaid.
$('rankPrevBtn').hidden = overlaid;
$('rankNextBtn').hidden = overlaid;
}
// Co-renders every rank in the SAME Mol* scene as independent layers -- reuses the exact
// layers/renderLayers machinery "Add to 3D" (Templates) already uses, so it's the same kind of
// unaligned co-render, not a real structural superposition: each rank is an independent sample
// from the model, with no guarantee it shares the primary's position/orientation. Toggling back
// drops every layer except the one currently shown by the scrubber.
function toggleRankOverlay() {
var primary = layers[0];
if (!primary || !primary.ranks || primary.ranks.length <= 1) return;
if (layers.length > 1) {
layers = [primary];
} else {
primary.ranks.forEach(function (text, i) {
if (i === primary.rankIndex) return; // already showing as the primary layer
var fmt = primary.format;
layers.push({ id: 'L' + (nextLayerId++), pdbId: primary.pdbId, label: 'Rank ' + (i + 1), text: text,
format: fmt, visible: true, parsed: fmt === 'pdb' ? parseResidues(text) : parseCifResidues(text),
isPrediction: true });
});
}
renderLayers(themeChosen).then(function () { buildSeqPanel(); renderLayersMenu(); });
}
$('rankOverlayBtn').onclick = toggleRankOverlay;
function setRank(delta) {
var L = layers[0];
if (!L || !L.ranks || L.ranks.length <= 1 || layers.length > 1) return;
var n = L.ranks.length;
L.rankIndex = (L.rankIndex + delta + n) % n;
L.text = L.ranks[L.rankIndex];
L.parsed = L.format === 'cif' ? parseCifResidues(L.text) : parseResidues(L.text);
confThreshold = null;
renderRankScrubber();
renderLayers(themeChosen).then(function () { buildSeqPanel(); });
}
$('rankPrevBtn').onclick = function () { setRank(-1); };
$('rankNextBtn').onclick = function () { setRank(1); };
// Renders EVERY visible layer into one shared Mol* scene: plugin.clear() once, then
// loadStructureFromData once per visible layer without clearing in between — this is the
// exact pattern the production /inference page already uses (inference.js's
// renderModelsMolstar) to show multiple structures at once, so it's a proven, not guessed,
// way to get co-rendering out of this same vendored Mol* build.
async function renderLayers(keepTheme) {
if (!layers.length) return;
var v = await ensureViewer();
try { await v.plugin.clear(); } catch (e) {}
var opts;
if (keepTheme) {
opts = { representationParams: { theme: { globalName: COLOR_MAP[curColor] || 'chain-id' }, type: { name: STYLE_MAP[curStyle] || 'cartoon' } } };
}
for (var i = 0; i < layers.length; i++) {
var L = layers[i]; if (!L.visible) continue;
// Component (polymer/ligand/water/ion) filtering is PDB-fixed-column text surgery — it
// does not apply to mmCIF results (e.g. a fresh prediction), which render unfiltered.
var fmt = L.format === 'cif' ? 'mmcif' : 'pdb';
var minConf = L.isPrediction ? confThreshold : null;
var text = L.format === 'cif' ? filterCifByConfidence(L.text, L.parsed, minConf) : filterByConfidence(filterPdbText(L.text, compHide), L.parsed, minConf);
try {
if (opts) await v.loadStructureFromData(text, fmt, opts);
else await v.loadStructureFromData(text, fmt);
} catch (e) {
try { await v.loadStructureFromData(text, fmt); }
catch (e2) { setViewerMsg('Could not render ' + L.label + ' (' + e2.message + ').'); }
}
}
if (keepTheme) { applyThemeBestEffort(); applyStyleBestEffort(); } // secondary, independent attempts at recoloring/restyling
applyCanvasBackground();
}
// Light/dark background for the viewer canvas itself (not the page chrome) — uses Mol*'s
// core canvas3d.setProps, which is a much more stable API surface than the representation/
// theme manager above, since Color values are just plain 0xRRGGBB numbers under the hood.
var viewerLight = false;
function applyCanvasBackground() {
try {
var c3d = mstar && mstar.plugin && mstar.plugin.canvas3d;
if (!c3d) return;
c3d.setProps({ renderer: { backgroundColor: viewerLight ? 0xffffff : 0x0b0f14 }, transparentBackground: false });
} catch (e) { /* cosmetic only */ }
}
$('themeBtn').innerHTML = ICON_MOON;
$('themeBtn').onclick = function () {
viewerLight = !viewerLight;
$('themeBtn').classList.toggle('active', viewerLight);
$('themeBtn').innerHTML = viewerLight ? ICON_SUN : ICON_MOON;
applyCanvasBackground();
};
// Mol*'s built-in "uncertainty" theme is a generic crystallographic-B-factor/RMSF display
// ("Uncertainty/Disorder") -- its own default color-list + domain, verified empirically against
// a real pipeline prediction (real pLDDT 50-96, mean 92 -- genuinely high confidence) with a
// headless-browser screenshot, renders it almost entirely RED. That's an inverted/mismatched
// scale for pLDDT (where HIGH = good and should read blue, AlphaFold convention), not missing
// or bad data. Mol* does ship a dedicated "plddt-confidence" theme, but it requires
// ma_quality_assessment/ModelArchive mmCIF annotations this pipeline's plain PDB/CIF output
// doesn't carry, so it's not a safe drop-in. Forcing an explicit domain + color list on the
// SAME "uncertainty" theme (still reads the real B-factor column) is what actually fixed it,
// reverified the same way: same real job, correctly renders almost entirely blue with visible
// dips exactly at the structure's genuine lower-confidence residues.
var PLDDT_COLOR_PARAMS = { domain: [0, 100], list: { kind: 'interpolate', colors: [[0xff0000, 0], [0xffffff, 0.5], [0x0000ff, 1]] } };
function applyThemeBestEffort() {
// Best-effort real Mol* theming via its plugin state manager. Wrapped defensively: if this
// vendored build's manager API shape differs, this silently no-ops rather than breaking the
// (already-real) structure load/filter/download pipeline above.
try {
if (!mstar || !mstar.plugin || !mstar.plugin.managers) return;
var colorMap = { Chain: 'chain-id', Rainbow: 'polymer-index', pLDDT: 'uncertainty', Element: 'element-symbol' };
var color = curColor;
var mgr = mstar.plugin.managers.structure;
var comps = mgr && mgr.hierarchy && mgr.hierarchy.selection && mgr.hierarchy.selection.structures &&
mgr.hierarchy.selection.structures[0] && mgr.hierarchy.selection.structures[0].components;
if (comps && mgr.component && mgr.component.updateRepresentationsTheme) {
var themeName = colorMap[color] || 'chain-id';
var params = { color: themeName };
if (color === 'pLDDT') params.colorParams = PLDDT_COLOR_PARAMS;
mgr.component.updateRepresentationsTheme(comps, params);
}
} catch (e) { /* cosmetic only */ }
}
// Cartoon/Surface/Ball & stick never actually took effect: this vendored Mol* build's
// loadStructureFromData(data, format, opts) silently drops opts.representationParams (only
// opts.dataLabel is ever read -- confirmed by reading the bundled source) and always calls
// applyPreset(tree, "default"), so every layer always rendered with the default cartoon preset
// no matter what curStyle said. The Style buttons still visually toggled (setStyleBtn just
// flips a CSS class), which is why clicking looked like it "did nothing" rather than erroring.
// Same fix shape as applyThemeBestEffort just above: updateRepresentations (not the Theme
// variant) swaps the type.name param of the already-built representation post-hoc, on the real
// structure-component manager, instead of relying on the load-time option that gets ignored.
// Its update() REPLACES the transform's params wholesale rather than deep-merging (confirmed
// empirically: passing only {type:{name:...}} silently no-ops, never changing the rendered
// style) -- so the new type name has to be spliced into a copy of the representation's full
// current params, not passed on its own.
function applyStyleBestEffort() {
try {
if (!mstar || !mstar.plugin || !mstar.plugin.managers) return;
var mgr = mstar.plugin.managers.structure;
var comps = mgr && mgr.hierarchy && mgr.hierarchy.selection && mgr.hierarchy.selection.structures &&
mgr.hierarchy.selection.structures[0] && mgr.hierarchy.selection.structures[0].components;
var firstRepr = comps && comps[0] && comps[0].representations && comps[0].representations[0];
if (comps && firstRepr && mgr.component && mgr.component.updateRepresentations) {
var oldParams = firstRepr.cell.transform.params;
var newParams = Object.assign({}, oldParams, { type: Object.assign({}, oldParams.type, { name: STYLE_MAP[curStyle] || 'cartoon' }) });
mgr.component.updateRepresentations(comps, firstRepr, newParams);
}
} catch (e) { /* cosmetic only */ }
}
function syncCompUI() {
document.querySelectorAll('.comp-row').forEach(function (row) {
var key = row.dataset.c.toLowerCase(), off = !!compHide[key];
row.classList.toggle('off', off);
row.querySelector('.eye').innerHTML = off ? ICON_EYE_OFF : ICON_EYE_ON;
});
}
var curResKeys = [], curResidues = {};
var AA_COLOR = { R: '#4d96ff', K: '#4d96ff', H: '#4d96ff', D: '#ef476f', E: '#ef476f', S: '#6bcb77', T: '#6bcb77', N: '#6bcb77', Q: '#6bcb77', C: '#6bcb77', Y: '#6bcb77', A: '#ffb703', V: '#ffb703', L: '#ffb703', I: '#ffb703', P: '#ffb703', F: '#ffb703', M: '#ffb703', W: '#ffb703', G: '#ffb703' };
function seqColor(res) {
if (!res) return '';
if (res.kind === 'nt') return NT_COLOR[res.code] || '';
if (res.kind === 'aa') return AA_COLOR[res.code] || '';
return '';
}
// Picks the chain used for SS/.dbn/download purposes: the first chain that's mostly nucleic
// acid, falling back to the first chain overall (e.g. an all-protein structure).
function pickPrimaryChain(parsed) {
for (var i = 0; i < parsed.order.length; i++) {
var ch = parsed.order[i], keys = parsed.chains[ch];
var ntCount = keys.filter(function (k) { return parsed.residues[k].kind === 'nt'; }).length;
if (ntCount >= keys.length * 0.7) return ch;
}
return parsed.order[0];
}
// Shared renderer for one chain's colored sequence — used by both the 3D tab's SEQ strip
// (all chains of the primary layer, so complexes show every chain, not just the first) and
// the Seqs tab (every layer, main structure + any templates added via "Add to 3D").
function chainBlockHtml(chain, keys, residuesMap) {
var unit = keys.length && residuesMap[keys[0]].kind === 'aa' ? 'aa' : 'nt';
var spans = keys.map(function (k) {
var res = residuesMap[k], col = seqColor(res);
return '<span data-key="' + k + '"' + (col ? ' style="color:' + col + '"' : '') + '>' + res.code + '</span>';
}).join('');
return '<div class="sp-chain"><div class="sp-h">Chain ' + chain + ' · ' + keys.length + ' ' + unit + '</div><div class="sp-seq">' + spans + '</div></div>';
}
function wireChainClicks(container, residuesMap) {
container.querySelectorAll('.sp-seq span').forEach(function (el) {
el.onclick = function () {
container.querySelectorAll('.sp-seq span').forEach(function (s) { s.style.background = ''; s.style.color = seqColor(residuesMap[s.dataset.key]); });
el.style.background = 'rgba(47,214,167,.35)'; el.style.color = '#e8edf2';
tryFocusResidue(residuesMap[el.dataset.key]);
};
});
}
// Computes the primary-chain state (curResidues/curResKeys/curSeq — used by the SS tab and
// downloads) and, if the old inline strip markup is present, keeps it in sync too. The Seqs
// tab is now the primary way to view sequences, but this state computation still matters
// regardless of which UI shows it.
function buildSeqPanel() {
var L = layers[0];
var body = $('seqBody');
if (!L) { if (body) body.innerHTML = ''; return; }
var parsed = L.parsed;
if (!parsed) {
// Both PDB (parseResidues) and mmCIF (parseCifResidues) are handled -- this is a genuine
// parse failure (e.g. an unrecognized mmCIF column layout), not just "it's mmCIF".
curResidues = {}; curResKeys = []; curSeq = '';
if (body) body.innerHTML = '<div class="sp-empty">Could not parse this structure\'s residues.</div>';
return;
}
curResidues = parsed.residues;
var primaryChain = pickPrimaryChain(parsed);
curResKeys = parsed.chains[primaryChain] || [];
curSeq = curResKeys.map(function (k) { return curResidues[k].code; }).join('');
if (body) {
body.innerHTML = parsed.order.map(function (ch) { return chainBlockHtml(ch, parsed.chains[ch], parsed.residues); }).join('');
wireChainClicks(body, parsed.residues);
}
}
// Loading a NEW primary structure (fetch/thread open) replaces the whole layer stack.
async function loadStructure(pdbId, label) {
pdbId = String(pdbId || '').toUpperCase().trim();
if (!pdbId) return;
setViewerMsg('Loading ' + pdbId + ' from RCSB…');
$('viewerName').textContent = label || pdbId;
try {
var text = await fetchPdbText(pdbId);
var newLayer = { id: 'L' + (nextLayerId++), pdbId: pdbId, label: label || pdbId, text: text, visible: true, parsed: parseResidues(text), pinned: false };
// Pinned layers (see toggleLayerPinned) survive a fresh load instead of being wiped by it --
// the whole point of pinning is to compare a structure against whatever gets loaded next,
// including from a different discussion. Unpinned ones are dropped, same as before.
layers = [newLayer].concat(layers.filter(function (l) { return l.pinned; }));
syncPrimaryAliases();
compHide = { polymer: false, ligand: false, water: false, ion: false };
confThreshold = null;
syncCompUI();
await renderLayers(themeChosen);
buildSeqPanel();
renderLayersMenu();
setViewerMsg('');
return true;
} catch (e) {
setViewerMsg('Could not load ' + pdbId + ' from RCSB (' + e.message + '). This needs outbound internet from your browser — no RNAnix backend involved.');
return false;
}
}
// "Add to 3D" from Templates — appends an overlay layer instead of replacing the primary one.
async function addLayer(pdbId, label) {
pdbId = String(pdbId || '').toUpperCase().trim();
if (!pdbId) return false;
if (!layers.length) return loadStructure(pdbId, label);
setViewerMsg('Adding ' + pdbId + '…');
try {
var text = await fetchPdbText(pdbId);
layers.push({ id: 'L' + (nextLayerId++), pdbId: pdbId, label: label || pdbId, text: text, visible: true, parsed: parseResidues(text), pinned: false });
await renderLayers(themeChosen);
renderLayersMenu();
$('displayMenu').hidden = false;
setViewerMsg('');
return true;
} catch (e) {
setViewerMsg('Could not add ' + pdbId + ' from RCSB (' + e.message + ').');
return false;
}
}
function removeLayer(id) {
layers = layers.filter(function (l) { return l.id !== id; });
syncPrimaryAliases();
if (!layers.length) {
try { mstar && mstar.plugin.clear(); } catch (e) {}
$('viewerName').textContent = 'No structure loaded';
setViewerMsg('No structure loaded — try a chat message like “fetch 1EHZ”.');
} else renderLayers(themeChosen);
renderLayersMenu();
buildSeqPanel();
}
function toggleLayerVisible(id) {
var L = layers.filter(function (l) { return l.id === id; })[0]; if (!L) return;
L.visible = !L.visible;
renderLayers(themeChosen);
renderLayersMenu();
}
// A pinned layer survives loadStructure()/addPredictionLayer() replacing the rest of `layers`
// (see their .pinned filters) and survives switching to "New chat" (see render()'s `!t`
// branch) -- the point is comparing a structure against whatever gets loaded next, including
// from a completely different discussion, without it getting silently cleared out from under
// you. Pinning doesn't protect against explicit removal via the layer's own remove button.
function toggleLayerPinned(id) {
var L = layers.filter(function (l) { return l.id === id; })[0]; if (!L) return;
L.pinned = !L.pinned;
renderLayersMenu();
}
function renderLayersMenu() {
renderRankScrubber();
var wrap = $('dispLayers'); if (!wrap) return;
wrap.innerHTML = layers.length ? layers.map(function (L, i) {
return '<div class="disp-row">' +
'<span class="disp-dot" style="background:' + LAYER_COLORS[i % LAYER_COLORS.length] + '"></span>' +
'<span class="disp-name" title="' + L.label + '">' + L.label + '</span>' +
'<button class="disp-eye" data-act="vis" data-layer="' + L.id + '">' + (L.visible ? ICON_EYE_ON : ICON_EYE_OFF) + '</button>' +
'<button class="disp-pin' + (L.pinned ? ' active' : '') + '" data-act="pin" data-layer="' + L.id + '" title="' +
(L.pinned ? 'Pinned -- stays loaded when you switch discussions' : 'Pin -- keep this structure when you load another one, including from a different discussion') +
'">' + ICON_PIN + '</button>' +
(layers.length > 1 ? '<button class="disp-x" data-act="rm" data-layer="' + L.id + '" title="remove layer">×</button>' : '') +
'</div>';
}).join('') : '<div class="disp-empty">No structures loaded</div>';
wrap.querySelectorAll('[data-act="vis"]').forEach(function (b) { b.onclick = function (e) { e.stopPropagation(); toggleLayerVisible(b.dataset.layer); }; });
wrap.querySelectorAll('[data-act="pin"]').forEach(function (b) { b.onclick = function (e) { e.stopPropagation(); toggleLayerPinned(b.dataset.layer); }; });
wrap.querySelectorAll('[data-act="rm"]').forEach(function (b) { b.onclick = function (e) { e.stopPropagation(); removeLayer(b.dataset.layer); }; });
}
document.querySelectorAll('.comp-row .eye').forEach(function (btn) {
btn.onclick = async function () {
var row = btn.closest('.comp-row'), key = row.dataset.c.toLowerCase();
compHide[key] = !compHide[key]; syncCompUI();
if (layers.length) { setViewerMsg('Updating…'); await renderLayers(themeChosen); setViewerMsg(''); }
};
});
// Layers/components is a persistent panel, not a click-away dropdown like the download/attach
// menus — open by default so its options are visible immediately, and re-opened any time a
// layer is added (see addLayer) so a newly-added template is never hidden from view.
$('displayBtn').onclick = function (e) { e.stopPropagation(); $('displayMenu').hidden = !$('displayMenu').hidden; };
$('measureBtn').onclick = function () { $('measureBtn').classList.toggle('active'); toast('Measure mode is a UI stub in this mockup — click two atoms in the real app to measure a distance.'); };
$('seqAccHead').onclick = function () {
var open = $('seqPanel').hidden;
$('seqPanel').hidden = !open;
$('seqAccHead').classList.toggle('open', open);
};
// ================= secondary structure (real Nussinov fold, self-contained) =================
function canPair(a, b) { var p = a + b; return p === 'AU' || p === 'UA' || p === 'GC' || p === 'CG' || p === 'GU' || p === 'UG'; }
function nussinov(seq) {
var n = seq.length; if (n < 5) return '.'.repeat(n);
var dp = []; for (var i = 0; i < n; i++) dp.push(new Array(n).fill(0));
for (var len = 4; len < n; len++) {
for (var a = 0; a + len < n; a++) {
var b = a + len;
var best = dp[a + 1][b];
if (dp[a][b - 1] > best) best = dp[a][b - 1];
if (canPair(seq[a], seq[b]) && dp[a + 1][b - 1] + 1 > best) best = dp[a + 1][b - 1] + 1;
for (var k = a + 1; k < b; k++) { var s = dp[a][k] + dp[k + 1][b]; if (s > best) best = s; }
dp[a][b] = best;
}
}
var pairs = [];
(function trace(i, j) {
if (i >= j) return;
if (dp[i][j] === dp[i + 1][j]) return trace(i + 1, j);
if (dp[i][j] === dp[i][j - 1]) return trace(i, j - 1);
if (canPair(seq[i], seq[j]) && dp[i][j] === dp[i + 1][j - 1] + 1) { pairs.push([i, j]); return trace(i + 1, j - 1); }
for (var k = i + 1; k < j; k++) { if (dp[i][j] === dp[i][k] + dp[k + 1][j]) { trace(i, k); trace(k + 1, j); return; } }
})(0, n - 1);
var db = new Array(n).fill('.');
pairs.forEach(function (p) { db[p[0]] = '('; db[p[1]] = ')'; });
return db.join('');
}
function dbnToPairs(db) {
var stack = [], pairs = [];
for (var i = 0; i < db.length; i++) {
if (db[i] === '(') stack.push(i);
else if (db[i] === ')') { var j = stack.pop(); if (j !== undefined) pairs.push([j, i]); }
}
return pairs;
}
// Real base pairs detected geometrically from the loaded structure's actual 3D coordinates
// (canonical pairing + a distance band around the ~10.4 Å C1'-C1' spacing typical of a WC/
// wobble pair), rather than purely from sequence — this is what lets pseudoknots show up at
// all, since a sequence-only nested fold (Nussinov, above) can never represent one.
function geometricPairs(seq, pts) {
var n = seq.length, cand = [], MIN_LOOP = 3, DMIN = 8, DMAX = 13, IDEAL = 10.4;
for (var i = 0; i < n; i++) {
for (var j = i + MIN_LOOP + 1; j < n; j++) {
if (!canPair(seq[i], seq[j])) continue;
var dx = pts[i][0] - pts[j][0], dy = pts[i][1] - pts[j][1], dz = pts[i][2] - pts[j][2];
var d = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (d >= DMIN && d <= DMAX) cand.push([i, j, Math.abs(d - IDEAL)]);
}
}
cand.sort(function (a, b) { return a[2] - b[2]; });
var used = new Array(n).fill(false), pairs = [];
cand.forEach(function (c) { if (!used[c[0]] && !used[c[1]]) { used[c[0]] = true; used[c[1]] = true; pairs.push([c[0], c[1]]); } });
return pairs;
}
function ssub(a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; }
function scross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; }
function snorm(a) { var l = Math.sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]) || 1; return [a[0] / l, a[1] / l, a[2] / l]; }
function hashFrac(seedStr) {
var h = 2166136261;
for (var i = 0; i < seedStr.length; i++) { h ^= seedStr.charCodeAt(i); h = (h * 16777619) >>> 0; }
return (h % 10000) / 10000;
}
// Illustrative reactivity, not measured — but not arbitrary either: real SHAPE/DMS chemical
// mapping strongly anti-correlates with base-pairing, so paired residues get a low value and
// unpaired ones a high value (deterministic per-residue jitter, not Math.random, so it's
// reproducible across renders of the same structure).
function syntheticReactivity(pairedFlag, probeSeed) {
return pairedFlag.map(function (paired, i) {
var jitter = hashFrac(probeSeed + ':' + i);
return Math.min(1, paired ? 0.05 + 0.15 * jitter : 0.45 + 0.5 * jitter);
});
}
function computeSSData() {
if (!curResKeys.length) return null;
var ntCount = curResKeys.filter(function (k) { return curResidues[k].kind === 'nt'; }).length;
if (ntCount < curResKeys.length * 0.7) return { notNucleic: true };
var seq = curSeq, n = seq.length;
if (n > 300) return { tooLong: true };
var nestedSet = {};
dbnToPairs(nussinov(seq)).forEach(function (p) { nestedSet[p[0] + '-' + p[1]] = true; });
var pts = curResKeys.map(function (k) { var r = curResidues[k]; return [r.x, r.y, r.z]; });
var pairs = geometricPairs(seq, pts).map(function (p) { return [p[0], p[1], !nestedSet[p[0] + '-' + p[1]]]; });
var pairedFlag = new Array(n).fill(false);
pairs.forEach(function (p) { pairedFlag[p[0]] = true; pairedFlag[p[1]] = true; });
return { keys: curResKeys, residues: curResidues, seq: seq, pairs: pairs, pairedFlag: pairedFlag };
}
function centroidOf(ss) {
var n = ss.keys.length, sx = 0, sy = 0, sz = 0;
ss.keys.forEach(function (k) { var r = ss.residues[k]; sx += r.x; sy += r.y; sz += r.z; });
return [sx / n, sy / n, sz / n];
}
function getCameraBasis() {
try {
var cam = mstar && mstar.plugin && mstar.plugin.canvas3d && mstar.plugin.canvas3d.camera;
var st = cam && cam.state;
if (!st || !st.position || !st.target || !st.up) return null;
var fwd = snorm(ssub(st.target, st.position));
var right = snorm(scross(fwd, st.up));
var trueUp = scross(right, fwd);
return { right: right, up: trueUp, origin: st.target };
} catch (e) { return null; }
}
function projectPoints(ss, basis, origin) {
return ss.keys.map(function (k) {
var r = ss.residues[k], v = [r.x - origin[0], r.y - origin[1], r.z - origin[2]];
return [v[0] * basis.right[0] + v[1] * basis.right[1] + v[2] * basis.right[2],
v[0] * basis.up[0] + v[1] * basis.up[1] + v[2] * basis.up[2]];
});
}
function pairLineSvg(a, b, pk) {
var dash = pk ? ' stroke-dasharray="4,3"' : '', color = pk ? '#ef476f' : '#2fd6a7';
return '<line x1="' + a[0].toFixed(1) + '" y1="' + a[1].toFixed(1) + '" x2="' + b[0].toFixed(1) + '" y2="' + b[1].toFixed(1) + '" stroke="' + color + '" stroke-width="1.3" opacity="0.9"' + dash + '/>';
}
function renderArcSVG(ss) {
var n = ss.seq.length, pad = 14, w = Math.max(320, n * 7), h = 150, baseY = h - 24;
var stepX = (w - 2 * pad) / Math.max(1, n - 1);
var parts = ['<svg viewBox="0 0 ' + w + ' ' + h + '" width="100%" height="' + h + '">'];
parts.push('<line x1="' + pad + '" y1="' + baseY + '" x2="' + (w - pad) + '" y2="' + baseY + '" stroke="#5c6773" stroke-width="1.5"/>');
ss.pairs.forEach(function (p) {
var xi = pad + p[0] * stepX, xj = pad + p[1] * stepX, r = (xj - xi) / 2;
var dash = p[2] ? ' stroke-dasharray="4,3"' : '', color = p[2] ? '#ef476f' : '#2fd6a7';
parts.push('<path d="M ' + xi.toFixed(1) + ' ' + baseY + ' A ' + r.toFixed(1) + ' ' + Math.min(r, 55).toFixed(1) + ' 0 0 1 ' + xj.toFixed(1) + ' ' + baseY + '" fill="none" stroke="' + color + '" stroke-width="1.4"' + dash + '/>');
});
return parts.join('') + '</svg>';
}
function renderCircularSVG(ss) {
var n = ss.seq.length, size = 320, cx = size / 2, cy = size / 2, r = size / 2 - 22;
var pts = []; for (var i = 0; i < n; i++) { var ang = (i / n) * Math.PI * 2 - Math.PI / 2; pts.push([cx + r * Math.cos(ang), cy + r * Math.sin(ang)]); }
var parts = ['<svg viewBox="0 0 ' + size + ' ' + size + '" width="100%" height="' + size + '">'];
parts.push('<path d="' + pts.map(function (p, i) { return (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1); }).join(' ') + '" fill="none" stroke="#5c6773" stroke-width="1.5"/>');
ss.pairs.forEach(function (p) { parts.push(pairLineSvg(pts[p[0]], pts[p[1]], p[2])); });
return parts.join('') + '</svg>';
}
function renderProjectionSVG(ss, basis, origin) {
var pts2 = projectPoints(ss, basis, origin);
var xs = pts2.map(function (p) { return p[0]; }), ys = pts2.map(function (p) { return p[1]; });
var minX = Math.min.apply(null, xs), maxX = Math.max.apply(null, xs), minY = Math.min.apply(null, ys), maxY = Math.max.apply(null, ys);
var w = 340, h = 260, pad = 22;
var s = Math.min((w - 2 * pad) / Math.max(1e-6, maxX - minX), (h - 2 * pad) / Math.max(1e-6, maxY - minY));
var mapped = pts2.map(function (p) { return [pad + (p[0] - minX) * s, h - pad - (p[1] - minY) * s]; });
var parts = ['<svg viewBox="0 0 ' + w + ' ' + h + '" width="100%" height="' + h + '">'];
parts.push('<path d="' + mapped.map(function (p, i) { return (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1); }).join(' ') + '" fill="none" stroke="#8a97a6" stroke-width="1.3"/>');
ss.pairs.forEach(function (p) { parts.push(pairLineSvg(mapped[p[0]], mapped[p[1]], p[2])); });
return parts.join('') + '</svg>';
}
function renderMotifLanes(ss) {
var seq = ss.seq, dms = syntheticReactivity(ss.pairedFlag, 'dms'), a2a3 = syntheticReactivity(ss.pairedFlag, '2a3');
function heat(v) { var g = Math.round(255 * (1 - v)); return 'rgb(255,' + g + ',' + g + ')'; }
function lane(label, cellsHtml) { return '<div class="lane"><span class="lane-lbl">' + label + '</span><div class="lane-cells">' + cellsHtml + '</div></div>'; }
var seqCells = seq.split('').map(function (c, i) { var col = seqColor(ss.residues[ss.keys[i]]) || '#8a97a6'; return '<span class="lane-cell lane-seq" style="color:' + col + '">' + c + '</span>'; }).join('');
var dmsCells = dms.map(function (v) { return '<span class="lane-cell" style="background:' + heat(v) + '" title="' + v.toFixed(2) + '"></span>'; }).join('');
var a2a3Cells = a2a3.map(function (v) { return '<span class="lane-cell" style="background:' + heat(v) + '" title="' + v.toFixed(2) + '"></span>'; }).join('');
var pairCells = ss.pairedFlag.map(function (p) { return '<span class="lane-cell" style="background:' + (p ? '#ffffff' : '#ffd7d7') + '"></span>'; }).join('');
return '<div class="motif-lanes">' + lane('Sequence', seqCells) + lane('DMS', dmsCells) + lane('2A3', a2a3Cells) + lane('Pairing', pairCells) + '</div>';
}
var ssMode = 'proj', ssPollTimer = null;
function renderSSPanel() {
var el = $('ssCanvas'), lanesEl = $('motifLanes'); if (!el) return;
var ss = computeSSData();
if (!ss) { el.innerHTML = '<div class="data-empty">Load a structure first (try “fetch 1EHZ” in the chat).</div>'; lanesEl.innerHTML = ''; return; }
if (ss.tooLong) { el.innerHTML = '<div class="data-empty">Sequence too long for the in-browser demo (>300 nt).</div>'; lanesEl.innerHTML = ''; return; }
if (ss.notNucleic) { el.innerHTML = '<div class="data-empty">Secondary-structure analysis applies to nucleic-acid chains — the loaded structure looks like a protein.</div>'; lanesEl.innerHTML = ''; return; }
var svg;
if (ssMode === 'arc') svg = renderArcSVG(ss);
else if (ssMode === 'circular') svg = renderCircularSVG(ss);
else if (ssMode === 'flatten') { var basis = getCameraBasis(); svg = basis ? renderProjectionSVG(ss, { right: basis.right, up: basis.up }, basis.origin) : renderProjectionSVG(ss, { right: [1, 0, 0], up: [0, 1, 0] }, centroidOf(ss)); }
else svg = renderProjectionSVG(ss, { right: [1, 0, 0], up: [0, 1, 0] }, centroidOf(ss));
el.innerHTML = svg;
lanesEl.innerHTML = renderMotifLanes(ss);
}
function setSSMode(m) {
ssMode = m;
document.querySelectorAll('.ssmode-btn').forEach(function (b) { b.classList.toggle('active', b.dataset.m === m); });
clearInterval(ssPollTimer); ssPollTimer = null;
if (m === 'flatten') ssPollTimer = setInterval(renderSSPanel, 200); // "follows the 3D viewer as you rotate it"
renderSSPanel();
}
document.querySelectorAll('.ssmode-btn').forEach(function (b) { b.onclick = function () { setSSMode(b.dataset.m); }; });
// ================= downloads =================
async function doDownload(kind) {
if (!curPdbId && kind !== 'msa') { toast('Load a structure first (try “fetch 1EHZ” in the chat).'); return; }
try {
if (kind === 'pdb') return downloadBlob(curPdbId + '.pdb', filterPdbText(curPdbText, compHide));
if (kind === 'cif') return downloadBlob(curPdbId + '.cif', await fetchCifText(curPdbId));
if (kind === 'png') {
var canvas = $('mstarContainer').querySelector('canvas');
if (!canvas) throw new Error('viewer canvas not ready yet');
return downloadDataUri(curPdbId + '.png', canvas.toDataURL('image/png'));
}
if (kind === 'dbn') {
if (!curSeq) throw new Error('no sequence extracted yet');
if (curSeq.length > 400) { toast('Sequence too long for the in-browser demo folder (>400 nt) — the real app would use a server-side folder.'); return; }
var db = nussinov(curSeq);
return downloadBlob(curPdbId + '.dbn', '>' + curPdbId + ' len=' + curSeq.length + ' (demo Nussinov fold — canonical WC/wobble pairs only, illustrative)\n' + curSeq + '\n' + db + '\n');
}
if (kind === 'zip') {
var files = [{ name: curPdbId + '.txt', data: _enc('structure: ' + curPdbId + '\ncomponents hidden: ' + JSON.stringify(compHide) + '\nfetched live from RCSB — no RNAnix backend\n') }];
files.push({ name: curPdbId + '.pdb', data: _enc(filterPdbText(curPdbText, compHide)) });
try { files.push({ name: curPdbId + '.cif', data: _enc(await fetchCifText(curPdbId)) }); } catch (e) {}
try { var c = $('mstarContainer').querySelector('canvas'); if (c) files.push({ name: curPdbId + '.png', data: dataURIBytes(c.toDataURL('image/png')) }); } catch (e) {}
if (curSeq && curSeq.length <= 400) files.push({ name: curPdbId + '.dbn', data: _enc('>' + curPdbId + '\n' + curSeq + '\n' + nussinov(curSeq) + '\n') });
return downloadZip(curPdbId + '_bundle.zip', files);
}
if (kind === 'pool') {
var pf = [{ name: 'README.txt', data: _enc('Simulated prediction pool for ' + curPdbId + ' (demo mockup — real pool comes from the Protenix pipeline, not this page).\n') }];
for (var s = 1; s <= 3; s++) for (var i = 0; i < 5; i++) pf.push({ name: 'seed_' + s + '/' + curPdbId + '_sample_' + i + '.pdb', data: _enc(filterPdbText(curPdbText, compHide)) });
return downloadZip(curPdbId + '_pool.zip', pf);
}
if (kind === 'msa') {
var recs = parseFasta($('msaInput').value);
if (!recs.length) { toast('Nothing in the MSA tab yet.'); return; }
return downloadBlob((curPdbId || 'alignment') + '.fasta', recs.map(function (r) { return '>' + r.name + '\n' + r.seq; }).join('\n') + '\n');
}
} catch (e) { toast('Download failed: ' + e.message); }
}
$('dlMain').onclick = function () { doDownload('zip'); };
$('dlCaret').onclick = function (e) { e.stopPropagation(); $('dlMenu').hidden = !$('dlMenu').hidden; };
document.addEventListener('click', function () { $('dlMenu').hidden = true; $('attachMenu').hidden = true; });
$('dlMenu').querySelectorAll('.dl-item').forEach(function (b) { b.onclick = function (e) { e.stopPropagation(); $('dlMenu').hidden = true; doDownload(b.dataset.k); }; });
// ================= tabs =================
function switchTab(tab) {
document.querySelectorAll('.vtab').forEach(function (b) { b.classList.toggle('active', b.dataset.tab === tab); });
document.querySelectorAll('.tabpanel').forEach(function (p) { p.classList.toggle('active', p.dataset.panel === tab); });
if (tab === 'ss') { renderSSPanel(); if (ssMode === 'flatten' && !ssPollTimer) ssPollTimer = setInterval(renderSSPanel, 200); }
else { clearInterval(ssPollTimer); ssPollTimer = null; }
}
document.querySelectorAll('.vtab').forEach(function (b) { b.onclick = function () { switchTab(b.dataset.tab); }; });
// Actually pulls the current tab's real data into the chat message as a labeled text block —
// same "compose, then insert" pattern as the entity modal — rather than just switching tabs
// and leaving the user to re-type everything by hand.
function attachToChat(kind) {
var block = '';
if (kind === 'chem') {
var vals = parseChemMap($('chemInput').value);
var range = vals.length ? Math.min.apply(null, vals).toFixed(2) + '–' + Math.max.apply(null, vals).toFixed(2) : 'n/a';
block = '[chemical mapping — 1D reactivity, ' + vals.length + ' residues, range ' + range + ']\n' + $('chemInput').value.trim();
} else if (kind === 'mohca') {
var n = $('mohcaInput').value.trim().split('\n').filter(Boolean).length;
block = '[MoHCA-seq — 2D contact map, ' + n + ' entries]\n' + $('mohcaInput').value.trim();
} else if (kind === 'templates') {
block = '[templates]\n' + TEMPLATES.map(function (t, i) {
return (i + 1) + ') ' + t.id + ' — ' + t.title + ' (' + t.identity + ' identity, ' + t.res + ', ' + t.method + ')' + (t.used ? ' [used as fold template]' : '');
}).join('\n');
} else if (kind === 'msa') {
var recs = parseFasta($('msaInput').value);
block = '[MSA — ' + recs.length + ' sequences]\n' + $('msaInput').value.trim();
}
if (!block) return;
var cur = $('msgInput').value;
$('msgInput').value = block + (cur.trim() ? '\n\n' + cur : '\n\n');
toast('Attached to message — review it in the input box before sending.');
}
$('attachBtn').onclick = function (e) { e.stopPropagation(); $('attachMenu').hidden = !$('attachMenu').hidden; };
$('attachMenu').querySelectorAll('button').forEach(function (b) {
b.onclick = function () { $('attachMenu').hidden = true; switchTab(b.dataset.tab); attachToChat(b.dataset.attach); $('msgInput').focus(); };
});
// ================= ChemMap (1D) — real parser + renderer =================
function parseChemMap(text) { return text.split(/[\s,]+/).map(Number).filter(function (v) { return isFinite(v); }); }
function renderChemTrack(values) {
if (!values.length) return '<div class="data-empty">No values yet — paste reactivity numbers above and click Visualize.</div>';
var max = Math.max.apply(null, values), min = Math.min.apply(null, values), span = (max - min) || 1;
return '<div class="track-row">' + values.map(function (v) {
var t = (v - min) / span, h = 8 + Math.round(t * 32), hue = 160 - Math.round(t * 160);
return '<div class="track-bar" style="height:' + h + 'px;background:hsl(' + hue + ',70%,50%)" title="' + v.toFixed(2) + '"></div>';
}).join('') + '</div>';
}
$('chemViz').onclick = function () { $('chemTrack').innerHTML = renderChemTrack(parseChemMap($('chemInput').value)); };
// ================= MoHCA-seq (2D) — real parser + renderer =================
function parseMohca(text) {
var lines = text.split('\n').map(function (l) { return l.trim(); }).filter(Boolean);
if (!lines.length) return null;
var isTriples = lines.every(function (l) { return l.split(/[\s,]+/).filter(Boolean).length === 3; });
if (isTriples) {
var triples = [], maxIdx = 0;
lines.forEach(function (l) { var p = l.split(/[\s,]+/).filter(Boolean).map(Number); triples.push(p); maxIdx = Math.max(maxIdx, p[0], p[1]); });
var n = maxIdx + 1, grid = []; for (var i = 0; i < n; i++) grid.push(new Array(n).fill(0));
triples.forEach(function (p) { grid[p[0]][p[1]] = p[2]; grid[p[1]][p[0]] = p[2]; });
return grid;
}
return lines.map(function (l) { return l.split(/[\s,]+/).filter(Boolean).map(Number); });
}
// Solid HSL interpolation (dark navy -> teal -> hot red), not alpha blending — a v=0 cell must
// still render as a real dark matrix cell, not a transparent hole in the grid, or the whole
// heatmap looks broken/blank except for the handful of explicitly-scored pairs.
function heatColor(t) {
// navy -> teal -> (via blue/purple/magenta, never green/yellow) -> red, so low and high
// values both stay visually distinct and "on brand" instead of muddy mid-tones.
t = Math.max(0, Math.min(1, t));
var light = 12 + Math.round(t * 42);
var hue = t < 0.5 ? (220 - Math.round((t / 0.5) * (220 - 166))) : ((166 + Math.round(((t - 0.5) / 0.5) * (360 - 166))) % 360);
return 'hsl(' + hue + ',72%,' + light + '%)';
}
function renderMohcaGrid(grid) {
if (!grid || !grid.length) return '<div class="data-empty">No contacts yet — paste i,j,score triples above and click Visualize.</div>';
var n = grid.length, flat = [].concat.apply([], grid), max = Math.max.apply(null, flat) || 1;
var cellPx = Math.max(3, Math.min(14, Math.floor(260 / n)));
var html = '<div class="mohca-axis">0</div><div class="mohca-inner" style="grid-template-columns:repeat(' + n + ',' + cellPx + 'px)">';
for (var i = 0; i < n; i++) for (var j = 0; j < n; j++) {
var v = (grid[i] && grid[i][j]) || 0, t = Math.max(0, Math.min(1, v / max));
var bg = i === j ? '#3a4552' : heatColor(t);
html += '<div class="mohca-cell" style="width:' + cellPx + 'px;height:' + cellPx + 'px;background:' + bg + '" title="(' + i + ',' + j + ') ' + v.toFixed(2) + '"></div>';
}
return html + '</div><div class="mohca-axis mohca-axis-end">' + (n - 1) + '</div>';
}
$('mohcaViz').onclick = function () { $('mohcaGrid').innerHTML = renderMohcaGrid(parseMohca($('mohcaInput').value)); };
// ================= MSA — real FASTA parser + renderer =================
function parseFasta(text) {
var recs = [], cur = null;
text.split('\n').forEach(function (line) {
line = line.trim(); if (!line) return;
if (line[0] === '>') { cur = { name: line.slice(1).trim() || ('seq' + (recs.length + 1)), seq: '' }; recs.push(cur); }
else if (cur) cur.seq += line.replace(/\s/g, '');
});
return recs;
}
var NT_COLOR = { A: '#6bcb77', C: '#4d96ff', G: '#ffb703', U: '#ef476f', T: '#ef476f' };
function renderMsa(recs) {
if (!recs.length) return '<div class="data-empty">Paste aligned FASTA sequences above (same length, gaps as \'-\').</div>';
var maxLen = Math.max.apply(null, recs.map(function (r) { return r.seq.length; }));
return recs.map(function (r) {
var padded = r.seq + '-'.repeat(maxLen - r.seq.length);
return '<div class="msa-row"><span class="msa-name" title="' + r.name + '">' + r.name + '</span><span class="msa-seq">' +
padded.split('').map(function (c) { var col = NT_COLOR[c.toUpperCase()]; return '<span class="msa-nt" style="background:' + (col ? col + '33' : 'transparent') + ';color:' + (col || '#5c6773') + '">' + c + '</span>'; }).join('') +
'</span></div>';
}).join('');
}
$('msaViz').onclick = function () { $('msaWrap').innerHTML = renderMsa(parseFasta($('msaInput').value)); };
// ================= Templates tab =================
var TEMPLATES = [
{ id: '3P49', title: 'Top structural homolog (used as fold template)', identity: '68%', res: '2.10 Å', method: 'X-ray', used: true },
{ id: '3OWI', title: 'Secondary candidate — single-domain coverage', identity: '54%', res: '2.85 Å', method: 'X-ray', used: false },
{ id: '3OWZ', title: 'Tertiary candidate — partial coverage', identity: '49%', res: '3.05 Å', method: 'X-ray', used: false },
];
function renderTemplates() {
$('tplWrap').innerHTML = TEMPLATES.map(function (tpl) {
return '<div class="tpl-card' + (tpl.used ? ' used' : '') + '">' +
'<div class="tpl-h"><a class="tpl-id" href="https://www.rcsb.org/structure/' + tpl.id + '" target="_blank" rel="noopener">' + tpl.id + '</a>' +
(tpl.used ? '<span class="tpl-used-badge">used as template</span>' : '') + '</div>' +
'<div class="tpl-t">' + tpl.title + '</div>' +
'<div class="tpl-meta">' + tpl.identity + ' identity · ' + tpl.res + ' · ' + tpl.method + '</div>' +
'<div class="tpl-actions"><button class="mini-btn" data-add="' + tpl.id + '">Add to 3D</button>' +
'<a class="mini-btn" href="https://pubmed.ncbi.nlm.nih.gov/?term=' + encodeURIComponent(tpl.title.replace(/[()]/g, '') + ' RNA structure') + '" target="_blank" rel="noopener">Related papers ' + ICON_EXTLINK + '</a></div>' +
'</div>';
}).join('');
// Adds the template as a new overlay layer alongside whatever's already loaded, rather than
// replacing it — that's the point of "Add to 3D" vs. the old "View in 3D".
$('tplWrap').querySelectorAll('[data-add]').forEach(function (b) {
b.onclick = function () { switchTab('3d'); addLayer(b.dataset.add, b.dataset.add + ' (template)'); };
});