-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
589 lines (511 loc) · 21 KB
/
Copy pathindex.html
File metadata and controls
589 lines (511 loc) · 21 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
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CoffeeMol — Molecular Visualizer</title>
<meta name="description" content="A lightweight, embeddable molecular visualizer for PDB and mmCIF files. No WebGL required.">
<!-- Favicon & Icons -->
<link rel="icon" type="image/svg+xml" href="favicon.svg">
<link rel="apple-touch-icon" href="favicon.svg">
<!-- Open Graph / Social -->
<meta property="og:type" content="website">
<meta property="og:title" content="CoffeeMol — Molecular Visualizer">
<meta property="og:description" content="Embeddable molecular visualizer for HTML5 browsers. Renders structure files without WebGL or runtime dependencies.">
<meta property="og:image" content="traces/cm_output.jpg">
<link rel="manifest" href="manifest.json">
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<canvas id="coffeemolCanvas">Canvas Load Failed</canvas>
<div id="mol-info-display"></div>
<div class="spinner-container" id="spinner">
<div class="mol-spinner">
<div class="spinner-atom"></div>
<div class="spinner-atom"></div>
<div class="spinner-atom"></div>
<div class="spinner-bond"></div>
<div class="spinner-bond"></div>
<div class="spinner-bond"></div>
</div>
<div style="color: var(--accent); font-weight: 600; font-family: sans-serif; font-size: 14px;">Analyzing Molecule...</div>
</div>
<div id="drop-overlay"></div>
<div id="mol-panel">
<div id="mol-header">
<span class="panel-title"><span class="coffee">Coffee</span>Mol</span>
<div style="display: flex; gap: 4px;">
<div id="mol-panel-toggle" class="action-button" title="Minimize/Maximize">−</div>
<div id="mol-help-toggle" class="action-button" title="Help">?</div>
<div id="mol-settings-toggle" class="action-button" title="Settings">⚙</div>
</div>
</div>
<div id="mol-controls-container">
<div id="mol-picker">
<input id="pdb-input" type="text" placeholder="PDB ID e.g. 1KX5" spellcheck="false" autocomplete="off">
<button id="mol-load">Load</button>
<button id="mol-random" class="action-button" title="Random molecule">🎲</button>
</div>
<div class="control-group">
<label class="control-label">Representation</label>
<select id="mol-draw-method" class="action-button full-width">
<option value="ribbon">Ribbon</option>
<option value="cartoon">Cartoon</option>
<option value="tube">Tube</option>
<option value="surface">Surface</option>
<option value="both">Points + Lines</option>
<option value="lines">Lines</option>
<option value="points">Points</option>
</select>
</div>
<div class="control-group">
<label class="control-label">Color Mode</label>
<select id="mol-color-method" class="action-button full-width">
<option value="cpk">CPK (Element)</option>
<option value="chain">Chain</option>
<option value="ss">Secondary Structure</option>
<option value="b-factor">B-Factor (Temp)</option>
<option value="formal-charge">Formal Charge</option>
<option value="hydrophobicity">Hydrophobicity</option>
</select>
</div>
<div class="controls-row buttons-row">
<div id="reset" class="action-button secondary-button" style="flex: 1;">Reset View</div>
<div id="export-png" class="action-button secondary-button" style="flex: 1;">Export PNG</div>
</div>
<div id="mol-info">
<div id="mol-info-header">
<span>Structure Info</span>
<span class="toggle-icon">▼</span>
</div>
<div id="mol-title-display"></div>
<div id="mol-meta"></div>
</div>
</div>
</div>
<div id="rotation-panel">
<span id="rotation-label">Rotate</span>
<button class="action-button rot-axis" data-axis="X">X</button>
<button class="action-button rot-axis" data-axis="Y">Y</button>
<button class="action-button rot-axis" data-axis="Z">Z</button>
<button class="action-button" id="rot-stop">Stop</button>
</div>
</body>
<div id="help-panel" class="hidden">
<div class="settings-header">
<span class="panel-title">Help</span>
<div id="help-close" class="action-button">✕</div>
</div>
<div class="help-content">
<div class="help-section">
<div class="help-label">Controls</div>
<div class="help-row"><span>Rotate</span><span>Left Click + Drag</span></div>
<div class="help-row"><span>Pan</span><span>Shift + Click + Drag</span></div>
<div class="help-row"><span>Zoom</span><span>Scroll / Pinch</span></div>
<div class="help-row"><span>Re-center</span><span>Double Click</span></div>
<div class="help-row"><span>Measure</span><span>Right Click Atoms</span></div>
</div>
<div class="help-section">
<div class="help-label">Input</div>
<div class="help-text">Enter a 4-letter PDB ID (e.g. 1KX5) or drag and drop .pdb / .cif files directly onto the canvas.</div>
</div>
<div class="help-section" style="margin-top: 8px; border-top: 1px solid var(--border); padding-top: 10px;">
<a href="https://github.com/michaelgrosner/CoffeeMol" target="_blank" class="meta-link" style="font-size: 12px; display: flex; align-items: center; justify-content: center; gap: 4px;">
CoffeeMol on GitHub ↗
</a>
</div>
</div>
</div>
<div id="settings-panel" class="hidden">
<div class="settings-header">
<span class="panel-title">Settings</span>
<div id="settings-close" class="action-button">✕</div>
</div>
<div class="control-group">
<label class="control-label">Renderer Engine</label>
<select id="mol-renderer-type" class="action-button full-width">
<option value="2d">Canvas</option>
<option value="3d">Three.js (BETA)</option>
</select>
</div>
<div class="control-group">
<label class="control-label">Presets</label>
<select id="settings-theme" class="action-button full-width">
<option value="coffee">Coffee</option>
<option value="default">Default (Jmol)</option>
<option value="dracula">Dracula</option>
<option value="gruvboxDark">Gruvbox Dark</option>
<option value="highContrast">High Contrast</option>
<option value="modern">Modern</option>
<option value="molokai">Molokai</option>
<option value="monochrome">Monochrome</option>
<option value="neon">Neon</option>
<option value="nord">Nord</option>
<option value="oneDark">One Dark</option>
<option value="solarizedDark">Solarized Dark</option>
<option value="synthwave84">Synthwave '84</option>
<option value="tokyoNight">Tokyo Night</option>
</select>
</div>
<div class="control-group">
<label class="control-label">Element Colors</label>
<div class="color-picker-grid">
<div class="color-picker-item">
<label>C</label>
<input type="color" data-atom="C">
</div>
<div class="color-picker-item">
<label>N</label>
<input type="color" data-atom="N">
</div>
<div class="color-picker-item">
<label>O</label>
<input type="color" data-atom="O">
</div>
<div class="color-picker-item">
<label>S</label>
<input type="color" data-atom="S">
</div>
<div class="color-picker-item">
<label>P</label>
<input type="color" data-atom="P">
</div>
<div class="color-picker-item">
<label>H</label>
<input type="color" data-atom="H">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Secondary Structure</label>
<div class="color-picker-grid">
<div class="color-picker-item">
<label>Helix</label>
<input type="color" data-ss="helix">
</div>
<div class="color-picker-item">
<label>Sheet</label>
<input type="color" data-ss="sheet">
</div>
<div class="color-picker-item">
<label>Loop</label>
<input type="color" data-ss="loop">
</div>
</div>
</div>
<div class="controls-row" style="margin-top: 8px;">
<div id="settings-reset" class="action-button secondary-button" style="flex: 1;">Reset to Defaults</div>
</div>
</div>
<script src="CoffeeMol.js"></script>
<script>
const MAX_ATOM_COUNT = 100_000;
const RCSB_FILE_BASE = 'https://files.rcsb.org/download';
const RCSB_SEARCH = 'https://search.rcsb.org/rcsbsearch/v2/query';
const RCSB_META_BASE = 'https://data.rcsb.org/rest/v1/core/entry';
const RCSB_WWW_BASE = 'https://www.rcsb.org/structure';
// --- Initialization ---
const initialRenderer = localStorage.getItem('coffeemol_renderer_type') || '2d';
const viewer = CoffeeMol.create("#coffeemolCanvas", null, initialRenderer).autoResize();
viewer.resize(); // Initial resize to fill screen
// --- Service Worker ---
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js').catch(err => console.warn('SW registration failed:', err));
});
}
// --- UI Helpers ---
function toggleSpinner(show) {
document.getElementById('spinner').classList.toggle('active', show);
}
function updateTitle(name) {
const isLocal = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
const prefix = isLocal ? "[DEV] " : "";
document.title = name ? `${prefix}${name} — CoffeeMol` : `${prefix}CoffeeMol — Molecular Visualizer`;
}
// --- Persistence ---
const STORAGE_KEYS = {
RENDERER: 'coffeemol_renderer_type',
METHOD: 'coffeemol_draw_method',
COLOR: 'coffeemol_color_method',
COLLAPSED: 'coffeemol_meta_collapsed',
SETTINGS: 'coffeemol_custom_settings',
THEME: 'coffeemol_theme_name'
};
function initPersistence() {
const savedRenderer = localStorage.getItem(STORAGE_KEYS.RENDERER);
if (savedRenderer) {
document.getElementById('mol-renderer-type').value = savedRenderer;
}
const savedMethod = localStorage.getItem(STORAGE_KEYS.METHOD);
if (savedMethod) {
document.getElementById('mol-draw-method').value = savedMethod;
}
const savedColor = localStorage.getItem(STORAGE_KEYS.COLOR);
if (savedColor) {
document.getElementById('mol-color-method').value = savedColor;
}
const savedTheme = localStorage.getItem(STORAGE_KEYS.THEME);
if (savedTheme) {
document.getElementById('settings-theme').value = savedTheme;
}
const savedSettings = localStorage.getItem(STORAGE_KEYS.SETTINGS);
if (savedSettings) {
try {
const settings = JSON.parse(savedSettings);
viewer.setScheme(settings);
updateSettingsUI();
} catch (e) { console.error("Failed to load settings", e); }
}
const isCollapsed = localStorage.getItem(STORAGE_KEYS.COLLAPSED) === 'true';
if (isCollapsed) {
document.getElementById('mol-info').classList.add('collapsed');
document.querySelector('#mol-info-header .toggle-icon').textContent = '▶';
}
}
function saveRenderer(val) { localStorage.setItem(STORAGE_KEYS.RENDERER, val); }
function saveMethod(val) { localStorage.setItem(STORAGE_KEYS.METHOD, val); }
function saveColor(val) { localStorage.setItem(STORAGE_KEYS.COLOR, val); }
function saveCollapsed(val) { localStorage.setItem(STORAGE_KEYS.COLLAPSED, val); }
function saveTheme(val) { localStorage.setItem(STORAGE_KEYS.THEME, val); }
function saveSettings() {
localStorage.setItem(STORAGE_KEYS.SETTINGS, JSON.stringify(viewer.colorScheme));
}
function rgbToHex(rgb) {
return "#" + ((1 << 24) + (rgb[0] << 16) + (rgb[1] << 8) + rgb[2]).toString(16).slice(1);
}
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? [
parseInt(result[1], 16),
parseInt(result[2], 16),
parseInt(result[3], 16)
] : null;
}
function updateSettingsUI() {
const scheme = viewer.colorScheme;
document.querySelectorAll('#settings-panel input[type="color"]').forEach(input => {
const atom = input.getAttribute('data-atom');
const ss = input.getAttribute('data-ss');
if (atom && scheme.atom_colors[atom]) {
input.value = rgbToHex(scheme.atom_colors[atom]);
} else if (ss && scheme.ss_colors[ss]) {
input.value = rgbToHex(scheme.ss_colors[ss]);
}
});
}
// --- RCSB Integration ---
async function fetchRandomPdbId() {
const baseQuery = {
query: {
type: 'terminal',
service: 'text',
parameters: {
attribute: 'rcsb_entry_info.deposited_atom_count',
operator: 'less',
value: MAX_ATOM_COUNT,
},
},
return_type: 'entry',
};
const opts = { method: 'POST', headers: { 'Content-Type': 'application/json' } };
const countRes = await fetch(RCSB_SEARCH, { ...opts, body: JSON.stringify({ ...baseQuery, request_options: { paginate: { start: 0, rows: 0 } } }) });
const countData = await countRes.json();
const total = countData.total_count;
const start = Math.floor(Math.random() * total);
const res = await fetch(RCSB_SEARCH, { ...opts, body: JSON.stringify({ ...baseQuery, request_options: { paginate: { start, rows: 1 } } }) });
const data = await res.json();
return data.result_set[0].identifier;
}
async function fetchMeta(pdbId) {
const titleEl = document.getElementById('mol-title-display');
const metaEl = document.getElementById('mol-meta');
titleEl.textContent = pdbId;
metaEl.textContent = 'Loading…';
try {
const res = await fetch(`${RCSB_META_BASE}/${pdbId}`);
const data = await res.json();
const title = data?.struct?.title ?? '—';
const method = data?.rcsb_entry_info?.experimental_method ?? '—';
const resolution = data?.rcsb_entry_info?.resolution_combined?.[0];
const atoms = data?.rcsb_entry_info?.deposited_atom_count;
const released = data?.rcsb_accession_info?.initial_release_date?.slice(0, 10);
const keywords = data?.struct_keywords?.text;
titleEl.textContent = title;
const rows = [
['Method', method],
resolution ? ['Resolution', resolution.toFixed(2) + ' Å'] : null,
atoms ? ['Atoms', atoms.toLocaleString()] : null,
released ? ['Released', released] : null,
keywords ? ['Keywords', keywords] : null,
].filter(Boolean);
let html = rows.map(([k, v]) =>
`<div class="meta-row"><span class="meta-key">${k}</span><span class="meta-val">${v}</span></div>`
).join('');
// Add RCSB link
html += `<div class="meta-row"><span class="meta-key">Source</span><span class="meta-val"><a href="${RCSB_WWW_BASE}/${pdbId}" target="_blank" class="meta-link">RCSB.org ↗</a></span></div>`;
metaEl.innerHTML = html;
} catch {
metaEl.textContent = 'Metadata unavailable';
}
}
function loadPdb(pdbId) {
pdbId = pdbId.trim().toUpperCase();
if (!pdbId) return;
document.getElementById('pdb-input').value = pdbId;
const drawMethod = document.getElementById('mol-draw-method').value;
const colorMethod = document.getElementById('mol-color-method').value;
toggleSpinner(true);
updateTitle(pdbId);
// Reflect the loaded PDB in the URL so refresh and sharing work.
if (window.location.pathname.slice(1).toUpperCase() !== pdbId) {
history.pushState({ pdbId }, '', `/${pdbId}`);
}
// Prefer mmCIF (.cif)
viewer.loadNewStructure(`${RCSB_FILE_BASE}/${pdbId}.cif`, { drawMethod, colorMethod });
fetchMeta(pdbId).finally(() => toggleSpinner(false));
}
// Reload the structure when the user navigates back/forward.
window.addEventListener('popstate', e => {
const pdbId = e.state?.pdbId || window.location.pathname.slice(1).toUpperCase();
if (/^[0-9][A-Z0-9]{3}$/.test(pdbId)) loadPdb(pdbId);
});
// --- Drag and Drop ---
const dropOverlay = document.getElementById('drop-overlay');
window.addEventListener('dragover', e => {
e.preventDefault();
dropOverlay.style.display = 'flex';
});
window.addEventListener('dragleave', e => {
if (e.relatedTarget === null) dropOverlay.style.display = 'none';
});
window.addEventListener('drop', e => {
e.preventDefault();
dropOverlay.style.display = 'none';
const file = e.dataTransfer.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = event => {
const data = event.target.result;
const drawMethod = document.getElementById('mol-draw-method').value;
const colorMethod = document.getElementById('mol-color-method').value;
toggleSpinner(true);
viewer.clear();
viewer.loadFromData(data, file.name, { drawMethod, colorMethod });
document.getElementById('mol-title-display').textContent = file.name;
document.getElementById('mol-meta').textContent = `Local file: ${(file.size / 1024).toFixed(1)} KB`;
updateTitle(file.name);
toggleSpinner(false);
};
reader.readAsText(file);
});
// --- Events ---
document.getElementById('mol-load').addEventListener('click', () => {
loadPdb(document.getElementById('pdb-input').value);
});
document.getElementById('mol-random').addEventListener('click', () => {
fetchRandomPdbId().then(loadPdb).catch(e => console.error(e));
});
document.getElementById('pdb-input').addEventListener('keydown', e => {
if (e.key === 'Enter') loadPdb(e.target.value);
});
document.getElementById('mol-renderer-type').addEventListener('change', e => {
const val = e.target.value;
viewer.setRenderer(val);
viewer.drawAll();
saveRenderer(val);
});
document.getElementById('mol-draw-method').addEventListener('change', e => {
const val = e.target.value;
viewer.changeAllDrawMethods(val);
saveMethod(val);
});
document.getElementById('mol-color-method').addEventListener('change', e => {
const val = e.target.value;
viewer.changeInfoFromSelectors('all', 'colorMethod', val);
saveColor(val);
});
document.getElementById('reset').addEventListener('click', () => {
viewer.restoreToOriginal();
});
document.getElementById('export-png').addEventListener('click', () => {
const dataURL = viewer.exportImage(2);
const link = document.createElement('a');
const title = document.getElementById('mol-title-display').textContent || 'coffeemol';
link.download = `${title.replace(/\s+/g, '_')}.png`;
link.href = dataURL;
link.click();
});
document.getElementById('mol-info-header').addEventListener('click', () => {
const info = document.getElementById('mol-info');
const icon = document.querySelector('#mol-info-header .toggle-icon');
const isCollapsed = info.classList.toggle('collapsed');
icon.textContent = isCollapsed ? '▶' : '▼';
saveCollapsed(isCollapsed);
});
document.getElementById('mol-panel-toggle').addEventListener('click', () => {
const panel = document.getElementById('mol-panel');
const btn = document.getElementById('mol-panel-toggle');
const isMinimized = panel.classList.toggle('minimized');
btn.textContent = isMinimized ? '+' : '−';
});
document.querySelectorAll('.rot-axis').forEach(btn => {
btn.addEventListener('click', () => {
viewer.stopRotation();
viewer.timedRotation(btn.getAttribute('data-axis'), 16);
});
});
document.getElementById('rot-stop').addEventListener('click', () => viewer.stopRotation());
// --- Panels ---
document.getElementById('mol-help-toggle').addEventListener('click', () => {
document.getElementById('settings-panel').classList.add('hidden');
document.getElementById('help-panel').classList.toggle('hidden');
});
document.getElementById('help-close').addEventListener('click', () => {
document.getElementById('help-panel').classList.add('hidden');
});
document.getElementById('mol-settings-toggle').addEventListener('click', () => {
document.getElementById('help-panel').classList.add('hidden');
const panel = document.getElementById('settings-panel');
panel.classList.toggle('hidden');
if (!panel.classList.contains('hidden')) updateSettingsUI();
});
document.getElementById('settings-close').addEventListener('click', () => {
document.getElementById('settings-panel').classList.add('hidden');
});
document.getElementById('settings-theme').addEventListener('change', e => {
const themeName = e.target.value;
const scheme = CoffeeMol.colorSchemes[themeName];
if (scheme) {
viewer.setScheme(scheme);
updateSettingsUI();
saveSettings();
saveTheme(themeName);
}
});
document.querySelectorAll('#settings-panel input[type="color"]').forEach(input => {
input.addEventListener('input', e => {
const atom = input.getAttribute('data-atom');
const ss = input.getAttribute('data-ss');
const rgb = hexToRgb(e.target.value);
if (atom) {
viewer.setScheme({ atom_colors: { ...viewer.colorScheme.atom_colors, [atom]: rgb } });
} else if (ss) {
viewer.setScheme({ ss_colors: { ...viewer.colorScheme.ss_colors, [ss]: rgb } });
}
saveSettings();
});
});
document.getElementById('settings-reset').addEventListener('click', () => {
localStorage.removeItem(STORAGE_KEYS.SETTINGS);
window.location.reload();
});
// --- Init ---
initPersistence();
const _pathId = window.location.pathname.slice(1).toUpperCase();
if (/^[0-9][A-Z0-9]{3}$/.test(_pathId)) {
loadPdb(_pathId);
} else {
fetchRandomPdbId().then(loadPdb).catch(e => alert('Failed to load structure: ' + e));
}
</script>
</html>