-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathumap.js
More file actions
1858 lines (1648 loc) · 58.9 KB
/
umap.js
File metadata and controls
1858 lines (1648 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// umap.js
// This file handles the UMAP visualization and interaction logic.
import { albumManager } from "./album-manager.js";
import { exitSearchMode } from "./search-ui.js";
import { getImagePath, setSearchResults } from "./search.js";
import { getCurrentSlideIndex, slideState } from "./slide-state.js";
import {
setUmapExitFullscreenOnSelection,
setUmapShowHoverThumbnails,
setUmapShowLandmarks,
setUmapClickSelectsCluster,
state,
} from "./state.js";
import { debounce, getPercentile, isColorLight } from "./utils.js";
import { CLUSTER_PALETTE } from "./cluster-utils.js";
const UMAP_SIZES = {
big: { width: 800, height: 590 },
medium: { width: 440, height: 310 },
small: { width: 360, height: 210 },
fullscreen: { width: window.innerWidth, height: window.innerHeight },
};
const landmarkCount = 18; // Maximum number of non-overlapping landmarks to show at any time
const randomWalkMaxSize = 2000; // Max cluster size to use random walk ordering
const MARKER_UPDATE_IGNORE_WINDOW_MS = 1000; // Time window to ignore marker updates after manual navigation
let externalClickCallback = null;
let updateMarkerTimer = null;
let ignoreUpdatesUntil = 0;
let isCurationModeActive = false; // Track if curation panel is open
export function setUmapClickCallback(callback) {
externalClickCallback = callback;
}
// --------------------------------------------
let points = [];
let clusters = [];
let colors = [];
let mapExists = false;
let isShaded = false;
let umapWindowHasBeenShown = false; // Track if window has been shown at least once
let isFullscreen = true;
let lastUnshadedSize = "medium"; // Track last non-fullscreen size
const lastUnshadedPosition = { left: null, top: null }; // Track last position
let landmarksVisible = false;
let hoverThumbnailsEnabled = true; // default ON
// Helper to get current window size
function getCurrentWindowSize() {
const win = document.getElementById("umapFloatingWindow");
const width = parseInt(win.style.width, 10);
if (isFullscreen) {
return "fullscreen";
}
if (width >= UMAP_SIZES.big.width) {
return "big";
}
if (width >= UMAP_SIZES.medium.width) {
return "medium";
}
return "small";
}
// Helper to save current position
function saveCurrentPosition() {
const win = document.getElementById("umapFloatingWindow");
lastUnshadedPosition.left = win.style.left;
lastUnshadedPosition.top = win.style.top;
}
// --- Utility ---
function getClusterColor(cluster) {
if (cluster === -1) {
return "#cccccc";
}
const idx = clusters.indexOf(cluster);
return colors[idx % colors.length];
}
// --- Spinner UI ---
function showUmapSpinner() {
document.getElementById("umapSpinner").style.display = "block";
}
function hideUmapSpinner() {
document.getElementById("umapSpinner").style.display = "none";
}
// --- EPS Spinner Debounce ---
let epsUpdateTimer = null;
document.getElementById("umapEpsSpinner").oninput = async () => {
const eps = parseFloat(document.getElementById("umapEpsSpinner").value) || 0.07;
if (epsUpdateTimer) {
clearTimeout(epsUpdateTimer);
}
epsUpdateTimer = setTimeout(async () => {
await fetch("set_umap_eps/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ album: state.album, eps }),
});
state.dataChanged = true;
await fetchUmapData();
}, 1000);
};
// --- Caching Current Album ---
let cachedAlbum = null;
let cachedAlbumName = null;
async function getCachedAlbum() {
const currentAlbumName = state.album;
if (cachedAlbum && cachedAlbumName === currentAlbumName) {
return cachedAlbum;
}
cachedAlbum = await albumManager.getCurrentAlbum();
cachedAlbumName = currentAlbumName;
return cachedAlbum;
}
// --- Main UMAP Data Fetch and Plot ---
export async function fetchUmapData() {
if (mapExists && !state.dataChanged) {
return;
}
if (!state.album) {
return;
}
showUmapSpinner();
try {
const eps = parseFloat(document.getElementById("umapEpsSpinner").value) || 0.07;
const response = await fetch(`umap_data/${encodeURIComponent(state.album)}?cluster_eps=${eps}`);
points = await response.json();
// Compute clusters and colors
clusters = [...new Set(points.map((p) => p.cluster))];
colors = clusters.map((c, i) => CLUSTER_PALETTE[i % CLUSTER_PALETTE.length]);
// Compute axis ranges (1st to 99th percentile)
const xs = points.map((p) => p.x);
const ys = points.map((p) => p.y);
const xMin = getPercentile(xs, 1);
const xMax = getPercentile(xs, 99);
const yMin = getPercentile(ys, 1);
const yMax = getPercentile(ys, 99);
// Prepare marker arrays
const markerColors = points.map((p) => getClusterColor(p.cluster));
const markerAlphas = points.map((p) => (p.cluster === -1 ? 0.08 : 0.75));
// Main trace: all points
const allPointsTrace = {
x: points.map((p) => p.x),
y: points.map((p) => p.y),
mode: "markers",
type: "scattergl",
marker: {
color: markerColors,
opacity: markerAlphas,
size: 5,
},
customdata: points.map((p) => p.index),
name: "All Points",
hoverinfo: "none",
};
// Current image marker trace
const [globalIndex] = getCurrentSlideIndex();
const currentPoint = points.find((p) => p.index === globalIndex);
const currentImageTrace = currentPoint
? {
x: [currentPoint.x],
y: [currentPoint.y],
text: ["Current slide: " + (await getImagePath(state.album, currentPoint.index)).split("/").pop()],
mode: "markers",
type: "scattergl",
marker: {
color: "#FFD700",
size: 18,
symbol: "circle-dot",
line: { color: "#000", width: 2 },
},
name: "Current Image",
hoverinfo: "text",
}
: {
x: [],
y: [],
text: [],
mode: "markers",
type: "scattergl",
marker: {
color: "#FFD700",
size: 18,
symbol: "circle-dot",
line: { color: "#000", width: 2 },
},
name: "Current Image",
hoverinfo: "none",
};
const layout = {
showlegend: false,
dragmode: "pan",
height: UMAP_SIZES.medium.height,
width: UMAP_SIZES.medium.width,
plot_bgcolor: "rgba(0,0,0,0)", // transparent plot area
paper_bgcolor: "rgba(0,0,0,0)", // transparent paper
font: { color: "#eee" },
xaxis: {
gridcolor: "rgba(255,255,255,0.15)",
zerolinecolor: "rgba(255,255,255,0.25)",
color: "#eee",
linecolor: "#888",
tickcolor: "#888",
range: [xMin, xMax],
scaleanchor: "y",
},
yaxis: {
gridcolor: "rgba(255,255,255,0.15)",
zerolinecolor: "rgba(255,255,255,0.25)",
color: "#eee",
linecolor: "#888",
tickcolor: "#888",
range: [yMin, yMax],
},
margin: {
t: 30,
r: 0,
b: 30,
l: 30,
pad: 0,
},
};
const config = {
modeBarButtons: [["zoom2d", "pan2d", "zoomIn2d", "zoomOut2d", "autoScale2d", "toImage"]],
scrollZoom: true,
};
Plotly.newPlot("umapPlot", [allPointsTrace, currentImageTrace], layout, config).then(async (gd) => {
document.getElementById("umapContent").style.display = "block";
setUmapWindowSize("fullscreen");
hideUmapSpinner();
window.dispatchEvent(new CustomEvent("umapRedrawn"));
await setUmapColorMode();
let hoverTimer = null;
let isHovering = false;
gd.on("plotly_hover", (eventData) => {
if (!hoverThumbnailsEnabled) {
return;
}
if (!eventData || !eventData.points || !eventData.points.length) {
return;
}
const pt = eventData.points[0];
// Use customdata to get the actual index, then find the point
const ptIndex = pt.customdata;
const point = points.find((p) => p.index === ptIndex);
const hoverCluster = point?.cluster ?? -1;
isHovering = true;
hoverTimer = setTimeout(() => {
if (isHovering) {
const landmarkCluster = findLandmarkCluster(pt);
let index, cluster;
if (landmarkCluster !== null) {
const clusterPoints = points.filter((p) => p.cluster === landmarkCluster);
const landmarkPoint = getLandmarkForCluster(clusterPoints);
index = landmarkPoint.index;
cluster = landmarkCluster;
} else {
index = ptIndex;
cluster = hoverCluster;
}
createUmapThumbnail({
x: eventData.event.clientX,
y: eventData.event.clientY,
index: index,
cluster: cluster,
});
}
}, 150);
});
gd.on("plotly_unhover", () => {
isHovering = false;
if (hoverTimer) {
clearTimeout(hoverTimer);
hoverTimer = null;
}
removeUmapThumbnail();
});
gd.on("plotly_relayout", (eventData) => {
if (suppressRelayoutEvent) {
return;
} // Prevent feedback loop
// Auto-switch back to pan after zoom
const isZoomEvent =
eventData["xaxis.range[0]"] !== undefined ||
eventData["yaxis.range[0]"] !== undefined ||
eventData["xaxis.range"] !== undefined ||
eventData["yaxis.range"] !== undefined;
if (isZoomEvent && gd.layout.dragmode === "zoom") {
// Small delay to avoid interfering with the zoom operation
setTimeout(() => {
Plotly.relayout(gd, { dragmode: "pan" });
}, 100);
}
// Only update landmarks for actual user pan/zoom events, not our programmatic changes
const isPanZoom =
eventData["xaxis.range[0]"] !== undefined ||
eventData["yaxis.range[0]"] !== undefined ||
eventData["xaxis.range"] !== undefined ||
eventData["yaxis.range"] !== undefined;
const isResize = eventData.width !== undefined || eventData.height !== undefined;
const isImageUpdate = eventData.images !== undefined;
// Only update landmarks for pan/zoom, not for our own image updates or resizes
if (isPanZoom && !isImageUpdate && !isResize) {
debouncedUpdateLandmarkTrace();
}
});
gd.on("plotly_redraw", () => {
if (suppressRelayoutEvent) {
return;
}
debouncedUpdateLandmarkTrace();
});
// Initial landmark update
if (landmarksVisible) {
setTimeout(updateLandmarkTrace, 500);
}
// Show the EPS spinner container now that the plot is ready
const epsContainer = document.getElementById("umapEpsContainer");
if (epsContainer) {
epsContainer.style.display = "block";
}
// After adding traces (e.g., landmarks), move the marker trace to the end
const plotDiv = document.getElementById("umapPlot");
const markerTraceIndex = plotDiv.data.findIndex((trace) => trace.name === "Current Image");
if (markerTraceIndex !== -1 && markerTraceIndex !== plotDiv.data.length - 1) {
Plotly.moveTraces(plotDiv, markerTraceIndex, plotDiv.data.length - 1);
}
});
// Ensure the current image marker is visible after plot initialization
setTimeout(() => updateCurrentImageMarker(), 0);
// Cluster click: highlight cluster as search
document.getElementById("umapPlot").on("plotly_click", async (data) => {
// --- MODIFIED: Intercept click for Curation Lock Mode ---
if (externalClickCallback) {
const pt = data.points[0];
let index = pt.customdata;
if (index === undefined && points[pt.pointIndex]) {
index = points[pt.pointIndex].index;
}
if (index !== undefined) {
externalClickCallback(index);
return; // Block normal search behavior
}
}
// ---------------------------------------------------
const clickedLandmarkCluster = findLandmarkCluster(data.points[0]);
if (clickedLandmarkCluster !== null) {
// Get all points in this cluster
const clusterPoints = points.filter((p) => p.cluster === clickedLandmarkCluster);
// Use the landmark placement algorithm to get the landmark point
const landmarkPoint = getLandmarkForCluster(clusterPoints);
if (landmarkPoint) {
// Check if we should select cluster or image
if (state.umapClickSelectsCluster) {
await handleClusterClick(landmarkPoint.index);
} else {
await handleImageClick(landmarkPoint.index);
}
}
} else {
const pt = data.points[0];
const traceName = pt.data?.name;
// Main points or highlighted points behave the same
if (traceName === "All Points" || traceName === "HighlightedPoints") {
// Check if we should select cluster or image
if (state.umapClickSelectsCluster) {
await handleClusterClick(pt.customdata);
} else {
await handleImageClick(pt.customdata);
}
}
}
});
window.umapPoints = points;
state.dataChanged = false;
// Dispatch event to notify that UMAP data has been loaded
window.dispatchEvent(new CustomEvent("umapDataLoaded"));
await setUmapColorMode();
} finally {
hideUmapSpinner();
}
mapExists = true;
}
function findLandmarkCluster(point) {
const plotDiv = document.getElementById("umapPlot");
const landmarkTraceIndex = plotDiv.data.findIndex((trace) => trace.name === "LandmarkClickTargets");
if (landmarkTraceIndex === -1) {
return null;
}
const landmarkTrace = plotDiv.data[landmarkTraceIndex];
const squareSize = Array.isArray(landmarkTrace.marker.size)
? landmarkTrace.marker.size[0]
: landmarkTrace.marker.size;
const plotWidthPx = plotDiv.offsetWidth || 800;
const plotHeightPx = plotDiv.offsetHeight || 560;
const xRange = plotDiv.layout.xaxis.range[1] - plotDiv.layout.xaxis.range[0];
const yRange = plotDiv.layout.yaxis.range[1] - plotDiv.layout.yaxis.range[0];
const halfSizeX = (squareSize / 2) * (xRange / plotWidthPx);
const halfSizeY = (squareSize / 2) * (yRange / plotHeightPx);
const landmarkXs = landmarkTrace.x;
const landmarkYs = landmarkTrace.y;
const landmarkClusters = landmarkTrace.customdata || [];
let foundLandmark = null;
for (let i = 0; i < landmarkXs.length; i++) {
if (Math.abs(point.x - landmarkXs[i]) <= halfSizeX && Math.abs(point.y - landmarkYs[i]) <= halfSizeY) {
foundLandmark = landmarkClusters[i] || null;
break;
}
}
return foundLandmark;
}
const plotDiv = document.getElementById("umapPlot");
plotDiv.addEventListener("mouseleave", () => {
removeUmapThumbnail();
});
// --- Dynamic Colorization ---
export async function colorizeUmap({ highlight = false, searchResults = [] } = {}) {
if (!points.length) {
return;
}
const plotDiv = document.getElementById("umapPlot");
if (!plotDiv || !plotDiv.data) {
return;
}
// Yield to the browser to allow spinner to render before heavy Plotly operations
await new Promise((resolve) => setTimeout(resolve, 0));
if (highlight && searchResults.length > 0) {
const searchSet = new Set(searchResults.map((r) => r.index));
// Split points into two groups
const regularPoints = points.filter((p) => !searchSet.has(p.index));
const highlightedPoints = points.filter((p) => searchSet.has(p.index));
// Update main trace with only regular points
await Plotly.restyle(
"umapPlot",
{
x: [regularPoints.map((p) => p.x)],
y: [regularPoints.map((p) => p.y)],
"marker.color": [regularPoints.map((p) => getClusterColor(p.cluster))],
"marker.opacity": [regularPoints.map((p) => (p.cluster === -1 ? 0.2 : 0.75))],
"marker.size": [regularPoints.map(() => 5)],
"marker.line.width": [0],
customdata: [regularPoints.map((p) => p.index)],
},
[0]
);
// Add/update highlighted trace
const highlightTraceIdx = plotDiv.data.findIndex((t) => t.name === "HighlightedPoints");
const highlightTrace = {
x: highlightedPoints.map((p) => p.x),
y: highlightedPoints.map((p) => p.y),
mode: "markers",
type: "scattergl",
marker: {
color: highlightedPoints.map((p) => getClusterColor(p.cluster)),
opacity: 1.0,
size: 8,
line: { width: 1, color: "#fff" },
},
customdata: highlightedPoints.map((p) => p.index),
name: "HighlightedPoints",
hoverinfo: "none",
};
if (highlightTraceIdx === -1) {
await Plotly.addTraces(plotDiv, [highlightTrace]);
} else {
await Plotly.restyle(
plotDiv,
{
x: [highlightTrace.x],
y: [highlightTrace.y],
"marker.color": [highlightTrace.marker.color],
"marker.opacity": [highlightTrace.marker.opacity],
"marker.size": [highlightTrace.marker.size],
customdata: [highlightTrace.customdata],
},
highlightTraceIdx
);
}
// Ensure Current Image marker stays on top
const markerTraceIndex = plotDiv.data.findIndex((trace) => trace.name === "Current Image");
if (markerTraceIndex !== -1 && markerTraceIndex !== plotDiv.data.length - 1) {
await Plotly.moveTraces(plotDiv, markerTraceIndex, plotDiv.data.length - 1);
}
} else {
// Remove highlight trace if it exists
const highlightTraceIdx = plotDiv.data?.findIndex((t) => t.name === "HighlightedPoints");
if (highlightTraceIdx !== -1) {
await Plotly.deleteTraces(plotDiv, highlightTraceIdx);
}
// Restore ALL points to main trace with normal coloring
const markerColors = points.map((p) => getClusterColor(p.cluster));
const markerAlphas = points.map((p) => (p.cluster === -1 ? 0.2 : 0.75));
const markerSizes = points.map(() => 5);
await Plotly.restyle(
"umapPlot",
{
x: [points.map((p) => p.x)],
y: [points.map((p) => p.y)],
"marker.color": [markerColors],
"marker.opacity": [markerAlphas],
"marker.size": [markerSizes],
"marker.line.width": [0],
customdata: [points.map((p) => p.index)],
},
[0]
);
// Ensure Current Image marker stays on top after removing highlight
const markerTraceIndex = plotDiv.data.findIndex((trace) => trace.name === "Current Image");
if (markerTraceIndex !== -1 && markerTraceIndex !== plotDiv.data.length - 1) {
await Plotly.moveTraces(plotDiv, markerTraceIndex, plotDiv.data.length - 1);
}
}
}
// --- Checkbox event handler ---
// Wait for state to be ready before initializing checkboxes
window.addEventListener("stateReady", () => {
const highlightCheckbox = document.getElementById("umapHighlightSelection");
if (highlightCheckbox) {
highlightCheckbox.checked = false;
highlightCheckbox.addEventListener("change", async () => {
await setUmapColorMode();
});
}
// Clear selection link
const clearSelectionLink = document.getElementById("umapClearSelectionLink");
if (clearSelectionLink) {
clearSelectionLink.addEventListener("click", (e) => {
e.preventDefault();
exitSearchMode();
});
}
// Hover thumbnails checkbox - initialize from state
const hoverThumbCheckbox = document.getElementById("umapShowHoverThumbnails");
if (hoverThumbCheckbox) {
hoverThumbCheckbox.checked = state.umapShowHoverThumbnails;
hoverThumbnailsEnabled = state.umapShowHoverThumbnails;
hoverThumbCheckbox.addEventListener("change", (e) => {
hoverThumbnailsEnabled = e.target.checked;
setUmapShowHoverThumbnails(e.target.checked);
// Remove any popup if disabling
if (!hoverThumbnailsEnabled) {
removeUmapThumbnail();
}
});
}
// Landmarks checkbox - initialize from state
const landmarkCheckbox = document.getElementById("umapShowLandmarks");
if (landmarkCheckbox) {
landmarkCheckbox.checked = state.umapShowLandmarks;
landmarksVisible = state.umapShowLandmarks;
landmarkCheckbox.addEventListener("change", (e) => {
landmarksVisible = e.target.checked;
setUmapShowLandmarks(e.target.checked);
updateLandmarkTrace();
});
}
// Exit fullscreen on selection checkbox - initialize from state
const exitFullscreenCheckbox = document.getElementById("umapExitFullscreenOnSelection");
if (exitFullscreenCheckbox) {
exitFullscreenCheckbox.checked = state.umapExitFullscreenOnSelection;
exitFullscreenCheckbox.addEventListener("change", (e) => {
setUmapExitFullscreenOnSelection(e.target.checked);
});
// Update enabled state based on fullscreen mode
updateExitFullscreenCheckboxState();
}
// Click behavior radio buttons - initialize from state
const clickSelectsClusterRadio = document.getElementById("umapClickSelectsClusterRadio");
const clickSelectsImageRadio = document.getElementById("umapClickSelectsImageRadio");
if (clickSelectsClusterRadio && clickSelectsImageRadio) {
// Set initial state
if (state.umapClickSelectsCluster) {
clickSelectsClusterRadio.checked = true;
} else {
clickSelectsImageRadio.checked = true;
}
// Add event listeners
clickSelectsClusterRadio.addEventListener("change", (e) => {
if (e.target.checked) {
setUmapClickSelectsCluster(true);
}
});
clickSelectsImageRadio.addEventListener("change", (e) => {
if (e.target.checked) {
setUmapClickSelectsCluster(false);
}
});
}
});
// Helper function to update the "Exit fullscreen on selection" checkbox state
function updateExitFullscreenCheckboxState() {
const exitFullscreenCheckbox = document.getElementById("umapExitFullscreenOnSelection");
const exitFullscreenLabel = document.getElementById("umapExitFullscreenLabel");
if (exitFullscreenCheckbox && exitFullscreenLabel) {
const shouldEnable = isFullscreen;
exitFullscreenCheckbox.disabled = !shouldEnable;
exitFullscreenLabel.style.opacity = shouldEnable ? "1" : "0.5";
}
}
// --- Update colorization after search or cluster selection ---
window.addEventListener("searchResultsChanged", async (e) => {
updateUmapColorModeAvailability(e.detail.results);
await setUmapColorMode();
// Hide spinner after colorization completes
hideUmapSpinner();
// deactivate fullscreen mode when search results have come in (if enabled)
if (state.searchResults.length > 0 && isFullscreen && state.umapExitFullscreenOnSelection) {
setTimeout(() => toggleFullscreen(false), 100); // slight delay to avoid flicker
}
});
window.addEventListener("slideChanged", async () => {
// Clear any existing pending update
if (updateMarkerTimer) {
clearTimeout(updateMarkerTimer);
}
updateMarkerTimer = setTimeout(() => {
// If we are currently inside the "Ignore Window" triggered by Clear, skip this update.
if (Date.now() < ignoreUpdatesUntil) {
return;
}
updateCurrentImageMarker();
}, 500);
});
// --- Update Current Image Marker ---
export async function updateCurrentImageMarker() {
if (!points.length) {
return;
}
const plotDiv = document.getElementById("umapPlot");
if (!plotDiv || !plotDiv.data) {
return;
}
// Find the trace index for the current image marker
const markerTraceIndex = plotDiv.data.findIndex((trace) => trace.name === "Current Image");
if (markerTraceIndex === -1) {
return;
}
const [globalIndex] = await getCurrentSlideIndex();
if (globalIndex === -1) {
return;
} // No current image
const currentPoint = points.find((p) => p.index === globalIndex);
if (!currentPoint) {
return;
}
// Always show the marker trace regardless of curation panel state
Plotly.restyle(
"umapPlot",
{
x: [[currentPoint.x]],
y: [[currentPoint.y]],
"marker.opacity": 1,
},
markerTraceIndex // Use the found index
);
ensureCurrentMarkerInView(0.1);
}
// --- Ensure Current Marker in View ---
export async function ensureCurrentMarkerInView(padFraction = 0.1) {
if (!points.length) {
return;
}
const plotDiv = document.getElementById("umapPlot");
if (!plotDiv || !plotDiv.layout) {
return;
}
const [globalIndex] = await getCurrentSlideIndex();
const currentPoint = points.find((p) => p.index === globalIndex);
if (!currentPoint) {
return;
}
const x = currentPoint.x;
const y = currentPoint.y;
let [xMin, xMax] = plotDiv.layout.xaxis.range;
let [yMin, yMax] = plotDiv.layout.yaxis.range;
let changed = false;
// Add a small padding so the marker isn't right at the edge
const xPad = (xMax - xMin) * padFraction;
const yPad = (yMax - yMin) * padFraction;
if (x < xMin + xPad || x > xMax - xPad) {
const xCenter = x;
const halfWidth = (xMax - xMin) / 2;
xMin = xCenter - halfWidth;
xMax = xCenter + halfWidth;
changed = true;
}
if (y < yMin + yPad || y > yMax - yPad) {
const yCenter = y;
const halfHeight = (yMax - yMin) / 2;
yMin = yCenter - halfHeight;
yMax = yCenter + halfHeight;
changed = true;
}
if (changed) {
Plotly.relayout(plotDiv, {
"xaxis.range": [xMin, xMax],
"yaxis.range": [yMin, yMax],
});
}
}
function ensureUmapWindowInView() {
const win = document.getElementById("umapFloatingWindow");
if (!win) {
return;
}
const rect = win.getBoundingClientRect();
const left = rect.left;
const top = rect.top;
// Ensure left/top are not negative
if (left < 0) {
win.style.left = "0px";
}
if (top < 0) {
win.style.top = "0px";
}
// Ensure top/left are not off-screen
const maxLeft = window.innerWidth - rect.width;
const maxTop = window.innerHeight - rect.height;
if (left > maxLeft) {
win.style.left = Math.max(0, maxLeft) + "px";
}
if (top > maxTop) {
win.style.top = Math.max(0, maxTop) + "px";
}
}
async function initializeUmapWindow() {
// Fetch the album's default EPS value and update the spinner
if (!state.album) {
return;
}
const result = await fetch("get_umap_eps/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ album: state.album }),
});
const data = await result.json();
if (data.success) {
const epsSpinner = document.getElementById("umapEpsSpinner");
if (epsSpinner) {
epsSpinner.value = data.eps;
}
}
state.dataChanged = true;
lastUnshadedSize = "medium"; // Reset to medium on album change
setSemanticMapTitle();
fetchUmapData();
toggleFullscreen(true); // Force fullscreen on album change
}
// --- Thumbnail Preview on Hover ---
let umapThumbnailDiv = null;
async function createUmapThumbnail({ x, y, index, cluster }) {
// Always remove any existing thumbnail before creating a new one
removeUmapThumbnail();
const filename = await getImagePath(state.album, index);
if (!filename) {
return;
} // No valid filename, exit early
// Find cluster color and calculate cluster size
const clusterColor = getClusterColor(cluster);
const clusterSize = points.filter((p) => p.cluster === cluster).length;
const clusterLabel = cluster === -1 ? "Unclustered" : `Cluster ${cluster} (size=${clusterSize})`;
const textIsDark = isColorLight(clusterColor) ? "#222" : "#fff";
const textShadow = isColorLight(clusterColor) ? "0 1px 2px #fff, 0 0px 8px #fff" : "0 1px 2px #000, 0 0px 8px #000";
// Build image URL (use thumbnail endpoint)
const imgUrl = `thumbnails/${state.album}/${index}?size=256`;
// Create the thumbnail div
umapThumbnailDiv = document.createElement("div");
umapThumbnailDiv.className = "umap-thumbnail";
umapThumbnailDiv.style.background = clusterColor; // keep dynamic color
// Thumbnail image
const img = document.createElement("img");
img.src = imgUrl;
img.alt = filename.split("/").pop();
umapThumbnailDiv.appendChild(img);
// Filename
const fnameDiv = document.createElement("div");
fnameDiv.className = "umap-thumbnail-filename";
fnameDiv.textContent = filename.split("/").pop();
fnameDiv.style.color = textIsDark;
fnameDiv.style.textShadow = textShadow;
umapThumbnailDiv.appendChild(fnameDiv);
// Cluster label
const clusterDiv = document.createElement("div");
clusterDiv.className = "umap-thumbnail-cluster";
clusterDiv.textContent = clusterLabel;
clusterDiv.style.color = textIsDark;
clusterDiv.style.textShadow = textShadow;
umapThumbnailDiv.appendChild(clusterDiv);
document.body.appendChild(umapThumbnailDiv);
// Position the window near the mouse pointer, but not off-screen
const pad = 12;
let left = x + pad;
let top = y + pad;
// Wait for the image to load before showing the div
img.onload = () => {
// Make sure the thumbnail div is still present in the DOM
if (!umapThumbnailDiv || !document.body.contains(umapThumbnailDiv)) {
return;
}
let rect = null;
try {
rect = umapThumbnailDiv.getBoundingClientRect();
} catch (e) {
console.warn("Error getting thumbnail div dimensions:", e);
return; // Exit if we can't get dimensions
}
if (left + rect.width > window.innerWidth - 10) {
left = x - rect.width - pad;
}
if (top + rect.height > window.innerHeight - 10) {
top = y - rect.height - pad;
}
umapThumbnailDiv.style.left = `${Math.max(0, left)}px`;
umapThumbnailDiv.style.top = `${Math.max(0, top)}px`;
umapThumbnailDiv.style.visibility = "visible"; // <-- Show after loaded
};
// Handle image load error
img.onerror = () => {
if (!umapThumbnailDiv || !document.body.contains(umapThumbnailDiv)) {
return;
}
umapThumbnailDiv.style.visibility = "visible";
img.alt = "Thumbnail not available";
};
}
function removeUmapThumbnail() {
// Remove all elements with the umap-thumbnail class
document.querySelectorAll(".umap-thumbnail").forEach((div) => div.remove());
umapThumbnailDiv = null;
}
export async function setUmapColorMode() {
await colorizeUmap({
highlight: document.getElementById("umapHighlightSelection")?.checked,
searchResults: state.searchResults,
});
}
// Ensure color mode is respected after search or cluster selection
window.addEventListener("searchResultsChanged", (e) => {
updateUmapColorModeAvailability(e.detail.results);
});
function updateUmapColorModeAvailability(searchResults = []) {
const highlightCheckbox = document.getElementById("umapHighlightSelection");
if (searchResults.length > 0) {
highlightCheckbox.disabled = false;
highlightCheckbox.parentElement.style.opacity = "1";
highlightCheckbox.checked = true; // Enable checkbox if there are search results
} else {
highlightCheckbox.checked = false; // Uncheck if no results
highlightCheckbox.disabled = true;
highlightCheckbox.parentElement.style.opacity = "0.5";
}
// Note: setUmapColorMode is called by the searchResultsChanged event handler
}
// ------------- Handling Landmark Thumbnails -------------
// Landmark placement algorithm
function getLandmarkForCluster(pts) {
// 1. Find X center
const centerX = pts.reduce((sum, p) => sum + p.x, 0) / pts.length;
// 2. Compute X spread (standard deviation and range)
const xs = pts.map((p) => p.x);
const xMean = centerX;
const xStd = Math.sqrt(xs.reduce((sum, x) => sum + Math.pow(x - xMean, 2), 0) / xs.length);
const xRange = Math.max(...xs) - Math.min(...xs);
// 3. Filter points near centerX (within 0.5 * std or 0.2 * range)
const threshold = Math.max(xStd * 0.5, xRange * 0.2);
const candidates = pts.filter((p) => Math.abs(p.x - centerX) <= threshold);
// 4. Pick highest Y among candidates
let best = candidates[0] || pts[0];
for (const p of candidates) {
if (p.y > best.y) {
best = p;
}
}
return best;
}
// Helper: get cluster centers and representatives
function getLargestClustersInView(maxLandmarks = 10) {
const plotDiv = document.getElementById("umapPlot");
if (!plotDiv || !plotDiv.layout) {
return [];
}
const [xMin, xMax] = plotDiv.layout.xaxis.range;
const [yMin, yMax] = plotDiv.layout.yaxis.range;
// Group points by cluster
const clusterMap = new Map();
points.forEach((p) => {
if (p.cluster === -1) {
return;
}
if (!clusterMap.has(p.cluster)) {
clusterMap.set(p.cluster, []);
}
clusterMap.get(p.cluster).push(p);
});