-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
750 lines (655 loc) · 34 KB
/
Copy pathindex.html
File metadata and controls
750 lines (655 loc) · 34 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Quantosaurus</title>
<meta name="description" content="A free, fast, completely client-side web tool for counting cells and biological image analysis. Train a lightweight model directly in your browser.">
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%22100%22>🦖</text></svg>">
<link rel="stylesheet" href="style.css">
</head>
<body class="mode-grab">
<div id="top-bar">
<h2>🦖 Quantosaurus</h2>
<div id="status">No images loaded. Drag & drop onto the canvas.</div>
<div style="flex: 1;"></div>
<button id="btnCheatsheet" class="btn-subtle">❓ Cheatsheet</button>
<button id="btnThemeToggle" class="btn-subtle">☀️ Light Mode</button>
<button id="btnFeedback" class="btn-subtle">💬 Feedback</button>
</div>
<div id="feedbackModal" class="modal-overlay" style="display: none;">
<div class="modal-content heavy-panel">
<div class="heavy-panel-header">
<span class="heavy-panel-title">Send Feedback</span>
<button id="btnCloseFeedback" class="img-delete" style="background:none; padding:2px 6px;">✕</button>
</div>
<p class="heavy-panel-desc" style="margin-bottom: 10px;">Help improve Quantosaurus! Let us know what's on your mind.</p>
<textarea id="feedbackText" placeholder="Love the tool, but export is slow..." rows="3" style="resize:none;"></textarea>
<input type="text" id="feedbackEmail" placeholder="Email address (optional)">
<label style="display:flex; align-items:center; gap:8px; font-size: 11px; color: var(--text-muted); margin-bottom: 12px; cursor: pointer;">
<input type="checkbox" id="chkDebug" checked>
Include technical debug info (browser, screen size, WebGPU support)
</label>
<div style="display:flex; justify-content:flex-end; gap:8px;">
<button id="btnSubmitFeedback" class="btn-primary" style="padding: 6px 12px;">Submit</button>
</div>
</div>
</div>
<div id="cheatsheetModal" class="modal-overlay" style="display: none;">
<div class="cheatsheet-paper">
<div class="cs-header">
<div>
<h1 style="margin: 0; font-size: 24px;">Welcome to Quantosaurus 🦖</h1>
<p style="margin: 4px 0 0 0; color: var(--text-muted); font-size: 14px;">
A free, <a href="https://github.com/Modjular/quantosaurus" target="_blank">open-source</a>, browser-based cell counter.
</p>
</div>
<div class="cs-header-actions">
<button id="btnPrintCheatsheet" class="btn-subtle" style="padding: 4px 10px; font-size: 12px;">🖨️ Print</button>
<button id="btnCloseCheatsheet" class="btn-close-cs" title="Close">✕</button>
</div>
</div>
<div class="cs-intro-grid">
<div class="cs-what-is-it">
<h3>What is it?</h3>
<p>Quantosaurus is a free, <strong>browser-based cell counter</strong> designed for rapid <strong>biological image analysis</strong>. It leverages <strong>interactive pixel classification</strong>—allowing you to train a lightweight machine learning model simply by painting on the canvas. It serves as a rapid, <strong>no-code cell counting</strong> tool that works beautifully for everything from <strong>Brightfield cell counting</strong> to fluorescence and <strong>DAPI cell counting</strong>.</p>
</div>
<div class="cs-privacy-banner">
<strong>🔒 Local & Private</strong>
<p style="margin: 6px 0 0 0;">Your images never leave your computer. All processing happens entirely client-side. No patient data or proprietary lab images are ever uploaded to a server.</p>
</div>
</div>
<div class="cs-section">
<h3>When to use Quantosaurus?</h3>
<p>Don't reach immediately for Quantosaurus; use the right tool for the job:</p>
<ul class="cs-list">
<li><strong>Use ImageJ/Fiji when:</strong> You just need simple, global thresholding.</li>
<li><strong>Use Cellpose when:</strong> You have complex, overlapping cells and the time/hardware to setup a neural net.</li>
<li><strong>Use Quantosaurus when:</strong> Thresholding fails, but you don't want to code. You just want to paint a few examples, train a lightweight model, and get a count instantly.</li>
</ul>
</div>
<div class="cs-section cs-instructions">
<h3>Instructions</h3>
<div class="cs-steps">
<div class="cs-step">
<div class="cs-step-number">1</div>
<div class="cs-step-text">
<strong>Choose Images</strong><br>
Drag your microscopy images (.tif, .png, .jpg) directly onto the canvas or use the file picker.
</div>
</div>
<div class="cs-step">
<div class="cs-step-number">2</div>
<div class="cs-step-text">
<strong>Paint Examples</strong><br>
Select the 🖌 Paint tool. Mark a few cells as 'Class 1' (Foreground) and mark the empty space as 'Class 2' (Background). The model only needs a few samples to start learning!
</div>
</div>
<div class="cs-step">
<div class="cs-step-number">3</div>
<div class="cs-step-text">
<strong>Get Counts</strong><br>
Adjust the <em>Feature Scale (Sigma)</em> if your cells are fuzzy or large. The model trains automatically. Counts appear next to their classes!
</div>
</div>
</div>
</div>
<div class="cs-section">
<h3>Hotkeys & Controls</h3>
<div class="cs-hotkeys">
<div class="hk-row"><span>Space + Drag</span><span>Pan around the image</span></div>
<div class="hk-row"><span>Mouse Wheel</span><span>Zoom in / out</span></div>
<div class="hk-row"><span>[ / ]</span><span>Decrease / Increase Brush Size</span></div>
<div class="hk-row"><span>1 - 9</span><span>Select Class 1 through 9</span></div>
<div class="hk-row"><span>P / E / G</span><span>Toggle Paint / Erase / Grab Tool</span></div>
</div>
</div>
<div class="cs-section">
<h3>Frequently Asked Questions</h3>
<div class="cs-faq">
<strong>Q: How do I get better segmentation results?</strong>
<p>A: Ensure you provide diverse examples. Paint both the bright centers and dim edges of cells, and explicitly label artifacts or dust as background (Class 2).</p>
<strong>Q: My browser crashed on export, why?</strong>
<p>A: Very large images (e.g., uncompressed .TIFs > 50MB) can exceed browser memory limits. Try downscaling your images before importing if you experience crashes.</p>
</div>
</div>
<div class="cs-footer">
<div>Built with 🦖 for Dr. Chen.</div>
<div style="display: flex; gap: 15px;">
<a href="https://github.com/Modjular/quantosaurus" target="_blank">GitHub</a>
<a href="https://forum.image.sc/" target="_blank">Image.sc Forum</a>
</div>
</div>
</div>
</div>
<div id="main-container">
<div id="sidebar">
<div class="sidebar-section" id="section-ingest">
<div class="section-header">Images</div>
<input type="file" id="fileInput" accept=".tif,.tiff,.png,.jpg,.jpeg"
multiple style="font-size:12px;">
<div id="img-empty">
Drop images onto the canvas<br>or use the file picker above.
</div>
<div id="image-list"></div>
</div>
<div class="sidebar-section" id="section-train">
<div class="section-header">Train</div>
<div class="control-group">
<span class="control-label">Tools</span>
<div style="display:flex; gap:10px; align-items:end;">
<div style="display:flex; gap:4px; flex:1;">
<button class="tool-btn active" data-tool="grab" title="Grab (Pan)">🖐</button>
<button class="tool-btn" data-tool="paint" title="Paint">🖌</button>
<button class="tool-btn" data-tool="erase" title="Erase">🧽</button>
</div>
</div>
</div>
<div class="control-group">
<span class="control-label">Brush Size</span>
<div style="display:flex; gap:10px; align-items:center;">
<input type="range" id="brushSizeRange" min="1" max="32" step="1" value="5">
<span id="brushVal" style="min-width:30px; font-size:12px;">5</span>
</div>
</div>
<div class="control-group">
<span class="control-label">Classes</span>
<div class="class-selector"></div>
</div>
<div class="control-group">
<span class="control-label">Feature Scale (Sigma)</span>
<div style="display:flex; gap:10px; align-items:center;">
<input type="range" id="sigmaRange" min="0.3" max="10.0" step="0.1" value="1.0">
<span id="sigmaVal" style="min-width:30px; font-size:12px;">1.0</span>
</div>
</div>
</div>
<div class="sidebar-section" id="section-export">
<div class="section-header">Export</div>
<div class="control-group">
<label style="display:flex; align-items:center; gap:8px; font-size: 13px;">
<input type="checkbox" id="chkExportSeg" checked>
Segmentations
</label>
<label style="display:flex; align-items:center; gap:8px; font-size: 13px;">
<input type="checkbox" id="chkExportProb">
Probabilities
</label>
</div>
<button id="btnExportAll" class="btn-primary" disabled>
Export Loaded Images
</button>
<p class="hint">
At least 5 labels are needed to train before export.
</p>
<button id="btnExportIlp" class="btn-primary" disabled>
Export ilastik Project (.ilp)
</button>
<div id="ilpSaveStatus" class="save-status"></div>
<p class="hint">
Fully self-contained — images and labels are embedded in the file. Opens in
desktop ilastik, which retrains its own classifier on open. Ctrl/Cmd+S to save.
</p>
</div>
</div>
<div id="viewport">
<div id="canvas-board"></div>
</div>
</div>
<script type="module">
import { DEFAULT_LABEL_COLORS, RF_CONFIG } from './js/config.js'
import { addFiles, redrawLabels, renderCentroids } from './js/images.js';
import { zipImages, exportIlp } from './js/export.js';
import { setupCamera } from './js/camera.js';
import { FlatRandomForest } from './js/rf.js';
import { scheduleTraining } from './js/training.js'
import { loadSettings, saveSettings } from './js/settings.js';
import { updateSaveIndicator } from './js/ui.js';
const state = {
// Images — ordered array; visual order == export order
images: [],
// ML
rf: new FlatRandomForest(RF_CONFIG),
// Presentation — per-class overlay colors, indexed by class. Owned by the
// UI (mutable), seeded from config defaults. The class *count* comes from
// rf.numClasses; colors are a separate concern that can change at runtime.
labelColors: [...DEFAULT_LABEL_COLORS],
// Per-class display names, indexed by class. Like labelColors, this is a
// UI-owned presentation concern (renamable at runtime, persisted to
// localStorage); the class *count* still comes from rf.numClasses.
classNames: Array.from({ length: RF_CONFIG.numClasses }, (_, i) => `Class ${i + 1}`),
// Whether each class's centroid markers are drawn on canvas (toggled via the
// class-item's swatch dot). Session-only — like camera/labels, not persisted.
classMarkersVisible: new Array(RF_CONFIG.numClasses).fill(true),
// Drawing / Tools
currentClass: 0,
isDrawing: false,
activeImageId: null,
toolMode: 'grab', // 'grab', 'paint', 'erase'
// Features
sigma: 1.0,
// Camera
camera: { x: 0, y: 0, scale: 1 },
isSpaceDown: false,
isPanning: false,
activePointerCount: 0,
// True while a debounced retrain+inference is running; drives the training
// progress cursor / status message (see setTrainingIndicator).
isTraining: false,
// Save state for the .ilp export (Ctrl+S). dirty tracks whether there
// are changes since the last successful save (set on image/label
// mutations in images.js, cleared by saveIlpProject); ilpFileHandle is
// the FileSystemFileHandle from a prior showSaveFilePicker() call, kept
// so repeat saves overwrite the same file instead of re-prompting
// (Chromium only — unset in browsers without the File System Access API).
dirty: false,
ilpFileHandle: null,
};
function init() {
const viewport = document.getElementById('viewport');
const board = document.getElementById('canvas-board');
setupCamera(state, viewport, board);
loadSettings(state); // restore persisted colors/names before the class UI renders
setupUI();
setupFeedback();
setupTheme();
// Guard against accidentally discarding work (loaded images + painted labels,
// none of which is persisted). Only prompt when there are actual unsaved
// changes — state.dirty tracks that precisely (see images.js's mutation
// points and saveIlpProject below), so this stays quiet right after a save.
window.addEventListener('beforeunload', (e) => {
if (state.dirty) {
e.preventDefault();
e.returnValue = '';
}
});
// Ctrl/Cmd+S saves the current project as an ilastik .ilp, regardless of
// focus (matches every other app's Save shortcut — even mid-rename of a
// class name). Runs before the "ignore while typing" hotkey guard below.
window.addEventListener('keydown', (e) => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
e.preventDefault();
saveIlpProject();
}
});
}
const ILP_PICKER_OPTS = {
types: [{ description: 'ilastik Project', accept: { 'application/octet-stream': ['.ilp'] } }],
};
/** Today's date as 'YYYYMMDD', for export filenames. */
function dateStamp() {
return new Date().toISOString().slice(0, 10).replace(/-/g, '');
}
/** Triggers a browser download of `blob` named `filename`. */
function downloadBlob(blob, filename) {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
URL.revokeObjectURL(link.href);
}
/**
* Writes `blob` to state.ilpFileHandle, prompting via showSaveFilePicker if
* there's no handle yet (Chromium only). Falls back to a plain download link
* in browsers without the File System Access API (Firefox, Safari), which
* re-prompts on every save since there's no persistent handle to reuse.
* Throws (with err.name === 'AbortError') if the user cancels the picker;
* clears state.ilpFileHandle and rethrows on any other write failure so the
* caller can retry once with a fresh picker (the old handle may be stale —
* revoked permission, or the file was moved/deleted).
*/
async function writeIlpBlob(blob) {
if (!('showSaveFilePicker' in window)) {
downloadBlob(blob, `quantosaurus_${dateStamp()}.ilp`);
return;
}
if (!state.ilpFileHandle) {
state.ilpFileHandle = await window.showSaveFilePicker({
suggestedName: `quantosaurus_${dateStamp()}.ilp`,
...ILP_PICKER_OPTS,
});
}
try {
const writable = await state.ilpFileHandle.createWritable();
await writable.write(blob);
await writable.close();
} catch (err) {
state.ilpFileHandle = null;
throw err;
}
}
/**
* Saves the current project as an ilastik .ilp — the Ctrl+S / "Export .ilp"
* button entry point. In Chromium, re-saves to the same file on repeat calls
* (via the File System Access API) instead of re-prompting every time.
*/
const ILP_BUTTON_LABEL = 'Export ilastik Project (.ilp)';
async function saveIlpProject() {
if (state.images.length === 0) return;
const btn = document.getElementById('btnExportIlp');
btn.disabled = true;
try {
const blob = exportIlp(state, { classNames: state.classNames });
try {
await writeIlpBlob(blob);
} catch (err) {
if (err.name === 'AbortError') return; // user cancelled the picker
await writeIlpBlob(blob); // handle was likely stale — retry once with a fresh picker
}
state.dirty = false;
updateSaveIndicator(state);
// Transient confirmation on the button itself — mirrors btnExportAll's
// existing pattern of repurposing its own label during an operation
// ('Training…'/'Exporting…'), just for success instead of progress.
btn.innerText = 'Saved ✓';
setTimeout(() => { if (btn.innerText === 'Saved ✓') btn.innerText = ILP_BUTTON_LABEL; }, 1200);
} catch (err) {
if (err.name === 'AbortError') return;
console.error(err);
alert(`ilastik project export failed: ${err.message}`);
} finally {
btn.disabled = false;
}
}
function setupTheme() {
const btnToggle = document.getElementById('btnThemeToggle');
const savedTheme = localStorage.getItem('quantosaurus-theme') || 'dark';
if (savedTheme === 'light') {
document.body.classList.add('theme-light');
btnToggle.innerHTML = '🌙 Dark Mode';
}
btnToggle.onclick = () => {
const isLight = document.body.classList.toggle('theme-light');
btnToggle.innerHTML = isLight ? '🌙 Dark Mode' : '☀️ Light Mode';
localStorage.setItem('quantosaurus-theme', isLight ? 'light' : 'dark');
};
}
function setupFeedback() {
const modal = document.getElementById('feedbackModal');
const btnOpen = document.getElementById('btnFeedback');
const btnClose = document.getElementById('btnCloseFeedback');
const btnSubmit = document.getElementById('btnSubmitFeedback');
const textarea = document.getElementById('feedbackText');
const emailInput = document.getElementById('feedbackEmail');
const chkDebug = document.getElementById('chkDebug');
btnOpen.onclick = () => {
modal.style.display = 'flex';
textarea.value = '';
emailInput.value = '';
textarea.focus();
};
const closeModal = () => modal.style.display = 'none';
btnClose.onclick = closeModal;
// Close modal if clicked outside content card
modal.onclick = (e) => {
if (e.target === modal) closeModal();
};
btnSubmit.onclick = async () => {
const content = textarea.value.trim();
const email = emailInput.value.trim();
if (!content) {
alert('Please enter your feedback before submitting.');
textarea.focus();
return;
}
// Pure regex validation for optional email
if (email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
alert('Please enter a valid email address, or leave it blank.');
emailInput.focus();
return;
}
}
btnSubmit.disabled = true;
btnSubmit.innerText = 'Sending…';
try {
// Build the payload dynamically
const payload = { content: content };
if (email) payload.email = email;
// Append technical context if the user opted in
if (chkDebug.checked) {
payload.context = {
userAgent: navigator.userAgent,
webGPU: !!navigator.gpu,
windowSize: `${window.innerWidth}x${window.innerHeight}`,
cores: navigator.hardwareConcurrency || 'unknown',
memoryGB: navigator.deviceMemory || 'unknown',
appState_imagesLoaded: state.images ? state.images.length : 0,
appState_activeTool: state.toolMode || 'unknown'
};
}
const response = await fetch("https://a.feedstick.app/feedback", {
method: "POST",
headers: {
"X-Feedstick-Key": "pk_live_4af6a5acafc943c18f763a863f12615f",
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
if (!response.ok) throw new Error('Network response failure.');
alert('Feedback submitted successfully! Thank you.');
closeModal();
} catch (err) {
console.error(err);
alert(`Could not send feedback: ${err.message}`);
} finally {
btnSubmit.disabled = false;
btnSubmit.innerText = 'Submit';
}
};
}
function setupUI() {
// Cheatsheet Modal
const modalCS = document.getElementById('cheatsheetModal');
const btnOpenCS = document.getElementById('btnCheatsheet');
const btnCloseCS = document.getElementById('btnCloseCheatsheet');
const btnPrintCS = document.getElementById('btnPrintCheatsheet')
modalCS.onclick = (e) => { if (e.target === modalCS) modalCS.style.display = 'none'; };
btnOpenCS.onclick = () => modalCS.style.display = 'flex';
btnCloseCS.onclick = () => modalCS.style.display = 'none';
btnPrintCS.onclick = () => window.print();
// Open cheatsheet if user hasn't visited before
if (!localStorage.getItem('quantosaurus-visited')) {
localStorage.setItem('quantosaurus-visited', 'true');
modalCS.style.display = 'flex';
}
// File input
document.getElementById('fileInput').onchange = (e) =>
addFiles(state, e.target.files).catch(console.error);
// Viewport drag-and-drop
const viewport = document.getElementById('viewport');
viewport.ondragover = (e) => { e.preventDefault(); viewport.classList.add('drag-active'); };
viewport.ondragleave = (e) => { e.preventDefault(); viewport.classList.remove('drag-active'); };
viewport.ondrop = (e) => {
e.preventDefault();
viewport.classList.remove('drag-active');
addFiles(state, e.dataTransfer.files).catch(console.error);
};
// Sigma
document.getElementById('sigmaRange').oninput = async (e) => {
state.sigma = parseFloat(e.target.value);
document.getElementById('sigmaVal').innerText = state.sigma.toFixed(1);
for (const img of state.images) {
await img.backend.updateFeatures(img.intensityArray, state.sigma);
}
scheduleTraining(state);
};
// Brush Size
const brushRange = document.getElementById('brushSizeRange');
const brushVal = document.getElementById('brushVal');
function setBrushSize(size) {
const clamped = Math.min(parseInt(brushRange.max, 10), Math.max(parseInt(brushRange.min, 10), size));
brushRange.value = clamped;
brushVal.innerText = clamped;
}
brushRange.oninput = () => setBrushSize(parseInt(brushRange.value, 10));
// Tools Setup (Grab, Paint, Erase)
function selectTool(tool) {
const btn = document.querySelector(`.tool-btn[data-tool="${tool}"]`);
if (!btn) return;
document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
state.toolMode = tool;
// Update body class for cursors
document.body.classList.remove('mode-grab', 'mode-paint', 'mode-erase');
document.body.classList.add(`mode-${state.toolMode}`);
}
document.querySelectorAll('.tool-btn').forEach(btn => {
btn.onclick = () => selectTool(btn.dataset.tool);
});
// Setup class selector with stat badges. The forest owns the class count
// (rf.numClasses); colors come from the mutable state.labelColors palette,
// falling back to neutral gray if fewer colors than classes are defined.
// The color swatch is a native <input type="color">, which always emits
// #rrggbb hex — state.labelColors entries are expected to stay hex from
// this point on so they round-trip through the picker cleanly.
document.querySelector('.class-selector').innerHTML =
Array.from({ length: state.rf.numClasses }, (_, index) => {
const color = state.labelColors[index] ?? '#888888';
const name = state.classNames[index] ?? `Class ${index + 1}`;
return `
<div class="class-item ${index === 0 ? 'active' : ''}" data-class="${index}">
<input type="color" class="color-box" data-class="${index}" value="${color}" title="Click to change color">
<span contenteditable data-class="${index}"></span>
<div class="class-count">
<span class="class-count-number" id="stat-class-${index}">0</span>
<button type="button"class="class-count-dot" id="dot-class-${index}" data-class="${index}"
title="Toggle markers on canvas" aria-pressed="true"></button>
</div>
</div>
`;
}).join('');
// Fill class names via textContent (not innerHTML above) so persisted, user-
// supplied names can't inject markup into the class selector.
document.querySelectorAll('.class-item span[contenteditable]').forEach(span => {
span.textContent = state.classNames[parseInt(span.dataset.class, 10)];
});
// Tint each class's swatch dot with its overlay color, matching the markers
// drawn over each object of that class.
for (let i = 0; i < state.rf.numClasses; i++) {
document.getElementById(`dot-class-${i}`)?.style.setProperty('--dot-color', state.labelColors[i] ?? '#888888');
}
// Class selector interaction
function selectClass(index) {
const el = document.querySelector(`.class-item[data-class="${index}"]`);
if (!el) return;
document.querySelectorAll('.class-item').forEach(i => i.classList.remove('active'));
el.classList.add('active');
state.currentClass = index;
}
document.querySelectorAll('.class-item').forEach(el => {
el.onclick = () => selectClass(parseInt(el.dataset.class, 10));
});
// Swatch dot — toggles that class's on-canvas centroid markers. Cheap: just
// re-runs the existing 2D canvas redraw from already-cached detected objects,
// no GPU/backend call or stats re-download.
document.querySelectorAll('.class-count-dot').forEach(dot => {
dot.onclick = (e) => {
e.stopPropagation(); // don't also re-select the class
const idx = parseInt(dot.dataset.class, 10);
const visible = !state.classMarkersVisible[idx];
state.classMarkersVisible[idx] = visible;
dot.classList.toggle('hidden', !visible);
dot.setAttribute('aria-pressed', String(visible));
state.images.forEach(img => renderCentroids(state, img));
};
});
// Class rename — persist on blur. Clicking into the name to edit shouldn't
// interfere with class selection (the item's onclick just marks it active).
// An empty/whitespace name falls back to the default so we never render a
// blank label or persist "".
document.querySelectorAll('.class-item span[contenteditable]').forEach(span => {
span.onblur = () => {
const idx = parseInt(span.dataset.class, 10);
const name = span.textContent.trim();
state.classNames[idx] = name || `Class ${idx + 1}`;
span.textContent = state.classNames[idx];
saveSettings(state);
};
});
// Class color pickers — recolor live as the user drags in the native
// picker (oninput, not change), mirroring how the contrast slider drives
// setWindow on every tick; setColors is just as cheap (uniform write + repaint).
document.querySelectorAll('.color-box').forEach(input => {
input.onclick = (e) => e.stopPropagation(); // don't also re-select the class
input.oninput = (e) => {
const idx = parseInt(input.dataset.class, 10);
state.labelColors[idx] = e.target.value;
document.getElementById(`dot-class-${idx}`)?.style.setProperty('--dot-color', e.target.value);
state.images.forEach(img => {
img.backend.setColors(state.labelColors);
redrawLabels(state, img);
// Repaint cached centroid markers so they recolor live too.
renderCentroids(state, img);
});
saveSettings(state);
};
});
// Hotkeys (see cheatsheet): [ / ] resize brush, 1-9 select class, P/E/G switch tool.
// Ignored while typing into an input/textarea or renaming a class (contenteditable).
window.addEventListener('keydown', (e) => {
const target = e.target;
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) return;
if (e.ctrlKey || e.metaKey || e.altKey) return;
if (e.key === '[') {
setBrushSize(parseInt(brushRange.value, 10) - 1);
} else if (e.key === ']') {
setBrushSize(parseInt(brushRange.value, 10) + 1);
} else if (e.key === 'p' || e.key === 'P' || e.key === 'b' || e.key === 'B') {
selectTool('paint');
} else if (e.key === 'e' || e.key === 'E') {
selectTool('erase');
} else if (e.key === 'g' || e.key === 'G') {
selectTool('grab');
} else if (e.key >= '1' && e.key <= '9') {
selectClass(parseInt(e.key, 10) - 1);
}
});
// Class name edits — persist into state.classNames on blur, mirroring
// how the color pickers persist into state.labelColors, so exports
// (e.g. exportIlp) can read live names straight off state.
document.querySelectorAll('.class-item span[contenteditable]').forEach((span, idx) => {
span.onblur = () => {
state.classNames[idx] = span.textContent.trim() || `Class ${idx + 1}`;
};
});
// Export
const btnExport = document.getElementById('btnExportAll');
btnExport.onclick = async () => {
const exportSeg = document.getElementById('chkExportSeg').checked;
const exportProb = document.getElementById('chkExportProb').checked;
if (!exportSeg && !exportProb) {
alert('Please select at least one export option.');
return;
}
btnExport.disabled = true;
btnExport.innerText = 'Training…';
try {
btnExport.innerText = 'Exporting…';
const zipBlob = await zipImages(
state.images,
exportSeg,
exportProb,
(metadata) => btnExport.innerText = metadata.percent.toFixed(2) + "%",
);
if (!zipBlob) throw Error('zip is empty, nothing to export')
downloadBlob(zipBlob, `ilastik_export_${dateStamp()}.zip`);
alert('All images exported successfully!');
} catch (err) {
console.error(err);
alert(`Export failed: ${err.message}`);
} finally {
btnExport.disabled = false;
btnExport.innerText = 'Export Loaded Images'
}
};
// Export .ilp — same entry point as Ctrl+S (see saveIlpProject above),
// reading class names from state.classNames (kept in sync with the
// class selector's contenteditable spans, see above).
document.getElementById('btnExportIlp').onclick = () => saveIlpProject();
}
init();
</script>
</body>
</html>