-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathalbum-manager.js
More file actions
1461 lines (1261 loc) · 46.4 KB
/
album-manager.js
File metadata and controls
1461 lines (1261 loc) · 46.4 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
// album-management.js
import { createSimpleDirectoryPicker } from "./filetree.js"; // Add this import
import { getIndexMetadata, removeIndex, updateIndex } from "./index.js";
import { exitSearchMode } from "./search-ui.js";
import { closeSettingsModal, loadAvailableAlbums, openSettingsModal } from "./settings.js";
import { setAlbum, state } from "./state.js";
import { hideSpinner, showSpinner } from "./utils.js";
export class AlbumManager {
// Constants
static POLL_INTERVAL = 1000;
static PROGRESS_HIDE_DELAY = 3000;
static AUTO_INDEXING_DELAY = 500;
static SETUP_EXIT_DELAY = 10000;
static FORM_ANIMATION_DELAY = 300;
static SCROLL_DELAY = 100;
static STATUS_CLASSES = {
SCANNING: "index-status scanning",
INDEXING: "index-status indexing",
UMAPPING: "index-status mapping",
COMPLETED: "index-status completed",
ERROR: "index-status error",
DEFAULT: "index-status",
};
constructor() {
this.overlay = document.getElementById("albumManagementOverlay");
this.albumsList = document.getElementById("albumsList");
this.template = document.getElementById("albumCardTemplate");
this.addAlbumSection = document.getElementById("addAlbumSection");
// Cache frequently used elements
this.elements = {
newAlbumKey: document.getElementById("newAlbumKey"),
newAlbumName: document.getElementById("newAlbumName"),
newAlbumDescription: document.getElementById("newAlbumDescription"),
newAlbumPathsContainer: document.getElementById("newAlbumPathsContainer"), // Changed this line
albumSelect: document.getElementById("albumSelect"),
slideshowTitle: document.getElementById("slideshow_title"),
albumManagementContent: document.querySelector("#albumManagementContent"),
};
this.progressPollers = new Map();
this.isSetupMode = false;
this.autoIndexingAlbums = new Set();
this.initializeEventListeners();
}
initializeEventListeners() {
// Main management button
const manageAlbumsBtn = document.getElementById("manageAlbumsBtn");
if (manageAlbumsBtn) {
manageAlbumsBtn.addEventListener("click", () => {
closeSettingsModal();
showSpinner();
this.show();
});
}
// Back to settings button
const backToSettingsBtn = document.getElementById("backToSettingsBtn");
if (backToSettingsBtn) {
backToSettingsBtn.addEventListener("click", () => {
this.hide();
openSettingsModal();
});
}
// Close button
document.getElementById("closeAlbumManagementBtn").addEventListener("click", () => {
this.hide();
});
// Show add album form button
document.getElementById("showAddAlbumBtn").addEventListener("click", () => {
this.showAddAlbumForm();
});
// Cancel add album buttons (both X and Cancel button)
document.getElementById("cancelAddAlbumBtn").addEventListener("click", () => {
this.hideAddAlbumForm();
});
document.getElementById("cancelAddAlbumBtn2").addEventListener("click", () => {
this.hideAddAlbumForm();
});
// Add album button
document.getElementById("addAlbumBtn").addEventListener("click", () => {
this.addAlbum();
});
// Click outside to close
this.overlay.addEventListener("click", (e) => {
if (e.target === this.overlay) {
this.hide();
}
});
// Edge cases
// - no albums configured
window.addEventListener("noAlbumsFound", () => {
this.enterSetupMode();
});
// no image files in selected album
window.addEventListener("albumIndexingNoImages", async (e) => {
const { albumKey } = e.detail;
await albumManager.show();
setTimeout(async () => {
const cardElement = document.querySelector(`.album-card[data-album-key="${albumKey}"]`);
if (cardElement) {
// Fetch the album object
const album = await albumManager.getAlbum(albumKey);
albumManager.editAlbum(cardElement, album);
// Show a user-friendly error message in the card
let errorDiv = cardElement.querySelector(".album-error-message");
if (!errorDiv) {
errorDiv = document.createElement("div");
errorDiv.className = "album-error-message";
cardElement.appendChild(errorDiv);
}
errorDiv.textContent =
"No image files were found in the provided paths. Please check your album paths and try again.";
errorDiv.style.color = "#b00020";
errorDiv.style.marginTop = "0.5em";
errorDiv.style.fontWeight = "bold";
cardElement.scrollIntoView({ behavior: "smooth", block: "center" });
}
}, 500);
});
// Handle missing/corrupted index errors and start indexing automatically
window.addEventListener("albumIndexError", async (e) => {
const { albumKey, errorType } = e.detail;
// Prevent duplicate auto-indexing for the same album
if (this.autoIndexingAlbums.has(albumKey)) {
console.log(`Auto-indexing already triggered for album: ${albumKey}`);
return;
}
this.autoIndexingAlbums.add(albumKey);
await albumManager.show();
setTimeout(async () => {
const cardElement = document.querySelector(`.album-card[data-album-key="${albumKey}"]`);
if (cardElement) {
// Show a user-friendly error message in the card
let errorDiv = cardElement.querySelector(".album-error-message");
if (!errorDiv) {
errorDiv = document.createElement("div");
errorDiv.className = "album-error-message";
cardElement.appendChild(errorDiv);
}
if (errorType === "missing") {
errorDiv.textContent = "This album's index is missing. Indexing will start automatically.";
} else if (errorType === "corrupted") {
errorDiv.textContent = "This album's index is corrupted. Indexing will start automatically.";
} else if (errorType === "outOfDate") {
errorDiv.textContent = "This album's index is out of date. Re-indexing will start automatically.";
} else {
errorDiv.textContent = "This album's index is corrupted or unreadable. Indexing will start automatically.";
}
errorDiv.style.color = "#b00020";
errorDiv.style.marginTop = "0.5em";
errorDiv.style.fontWeight = "bold";
cardElement.scrollIntoView({ behavior: "smooth", block: "center" });
// Automatically start indexing
await albumManager.startIndexing(albumKey, cardElement, errorType === "corrupted");
albumManager.showProgressUI(cardElement);
}
}, 500);
});
}
// Utility methods
async fetchAvailableAlbums() {
const response = await fetch("available_albums/");
return await response.json();
}
async getAlbum(albumKey) {
const response = await fetch(`album/${albumKey}/`);
return await response.json();
}
async refreshAlbumsAndDropdown() {
await this.loadAlbums();
await loadAvailableAlbums();
}
async updateCurrentAlbum(album) {
// Update state and localStorage
setAlbum(album.key);
// Update settings dropdown
await loadAvailableAlbums();
// Update page title
if (this.elements.slideshowTitle) {
this.elements.slideshowTitle.textContent = `Slideshow - ${album.name}`;
}
}
getNewAlbumFormData() {
return {
key: this.elements.newAlbumKey.value.trim(),
name: this.elements.newAlbumName.value.trim(),
description: this.elements.newAlbumDescription.value.trim(),
paths: this.collectNewAlbumPathFields(), // Changed this line
};
}
clearAddAlbumForm() {
this.elements.newAlbumKey.value = "";
this.elements.newAlbumName.value = "";
this.elements.newAlbumDescription.value = "";
// Clear path fields container
if (this.elements.newAlbumPathsContainer) {
this.elements.newAlbumPathsContainer.innerHTML = "";
}
}
// Form management
showAddAlbumForm() {
this.addAlbumSection.style.display = "block";
this.addAlbumSection.classList.remove("slide-up");
this.addAlbumSection.classList.add("slide-down");
// Initialize path fields for the add album form
this.initializeNewAlbumPathFields();
// Focus on the first input field
this.elements.newAlbumKey.focus();
}
hideAddAlbumForm() {
this.addAlbumSection.classList.remove("slide-down");
this.addAlbumSection.classList.add("slide-up");
// Hide the section after animation completes
setTimeout(() => {
this.addAlbumSection.style.display = "none";
this.clearAddAlbumForm();
}, AlbumManager.FORM_ANIMATION_DELAY);
}
// New methods for add album form
initializeNewAlbumPathFields() {
const container = this.elements.newAlbumPathsContainer;
if (container) {
container.innerHTML = "";
// Add one empty field to start
this.addNewAlbumPathField("");
}
}
addNewAlbumPathField(path = "") {
const container = this.elements.newAlbumPathsContainer;
if (container) {
const row = this.createNewAlbumPathField(path);
container.appendChild(row);
}
}
_createAlbumPathRow({ path = "", onAddRow, onRemoveRow, onFolderPick } = {}) {
const wrapper = document.createElement("div");
wrapper.className = "album-path-row";
wrapper.style.cssText = `
display: flex;
align-items: center;
margin-bottom: 0.5em;
gap: 0.5em;
`;
const input = document.createElement("input");
input.type = "text";
input.className = "album-path-input";
input.value = path;
input.placeholder = "Enter the path to a folder of images, or click the folder icon";
input.style.cssText = `
flex: 1;
background: #222;
color: #faea0e;
border: 1px solid #444;
border-radius: 4px;
padding: 8px;
`;
input.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
// Show the trash icon when Enter is pressed
trashBtn.style.display = "inline-block";
// Only add a new row if this is the last row
if (wrapper.nextElementSibling === null && typeof onAddRow === "function") {
onAddRow();
}
}
});
const folderBtn = document.createElement("button");
folderBtn.type = "button";
folderBtn.className = "open-folder-btn";
folderBtn.title = "Select folder";
folderBtn.innerHTML = "📁";
folderBtn.style.cssText = `
background: none;
border: none;
font-size: 1.2em;
cursor: pointer;
padding: 4px;
`;
folderBtn.onclick = () => {
const currentPath = input.value.trim();
if (typeof onFolderPick === "function") {
onFolderPick(currentPath, (selectedPath) => {
input.value = selectedPath;
trashBtn.style.display = "inline-block";
if (wrapper.nextElementSibling === null && typeof onAddRow === "function") {
onAddRow();
}
});
}
};
const trashBtn = document.createElement("button");
trashBtn.type = "button";
trashBtn.className = "remove-path-btn";
trashBtn.title = "Remove path";
trashBtn.innerHTML = "🗑️";
trashBtn.style.cssText = `
background: none;
border: none;
font-size: 1.2em;
cursor: pointer;
padding: 4px;
display: ${path ? "inline-block" : "none"};
`;
trashBtn.onclick = () => {
wrapper.remove();
if (typeof onRemoveRow === "function") {
onRemoveRow();
}
};
wrapper.appendChild(input);
wrapper.appendChild(folderBtn);
wrapper.appendChild(trashBtn);
return wrapper;
}
createNewAlbumPathField(path = "") {
const container = this.elements.newAlbumPathsContainer;
return this._createAlbumPathRow({
path,
container,
onAddRow: () => this.addNewAlbumPathField(""),
onRemoveRow: () => {
if (container && container.children.length === 0) {
this.addNewAlbumPathField("");
}
},
onFolderPick: (currentPath, setPath) => {
createSimpleDirectoryPicker(
(selectedPath) => {
setPath(selectedPath);
},
currentPath,
{ showCreateFolder: true }
);
},
});
}
createPathField(path = "", cardElement) {
const container = cardElement.querySelector(".edit-album-paths-container");
return this._createAlbumPathRow({
path,
container,
onAddRow: () => this.addPathField("", cardElement),
onRemoveRow: () => {
if (container && container.children.length === 0) {
this.addPathField("", cardElement);
}
},
onFolderPick: (currentPath, setPath) => {
createSimpleDirectoryPicker(
(selectedPath) => {
setPath(selectedPath);
},
currentPath,
{ showCreateFolder: true }
);
},
});
}
collectNewAlbumPathFields() {
const inputs = this.elements.newAlbumPathsContainer.querySelectorAll(".album-path-input");
return Array.from(inputs)
.map((input) => input.value.trim())
.filter((path) => path.length > 0);
}
// Main show/hide methods
async show() {
this.overlay.classList.add("visible");
hideSpinner();
await this.loadAlbums();
await this.checkForOngoingIndexing(); // <-- Move this after loadAlbums
// Ensure add album form is hidden when opening normally
if (!this.isSetupMode) {
this.addAlbumSection.style.display = "none";
this.addAlbumSection.classList.remove("slide-down", "slide-up");
}
}
hide() {
if (this.isSetupMode) {
console.log("Cannot close Album Manager - setup required");
return; // Don't allow closing in setup mode
}
this.overlay.classList.remove("visible");
this.hideAddAlbumForm();
// Stop all progress polling
this.progressPollers.forEach((interval) => {
clearInterval(interval);
});
this.progressPollers.clear();
}
// Setup mode management
async enterSetupMode() {
console.log("Entering setup mode - no albums found.");
this.isSetupMode = true;
await this.show();
this.showSetupMessage();
this.showAddAlbumForm();
this.disableClosing();
}
showSetupMessage() {
const existingMessage = this.overlay.querySelector(".setup-message");
if (existingMessage) {
return;
}
const setupMessage = this.createSetupMessage();
if (this.elements.albumManagementContent) {
this.elements.albumManagementContent.insertBefore(setupMessage, this.elements.albumManagementContent.firstChild);
}
}
createSetupMessage() {
const setupMessage = document.createElement("div");
setupMessage.className = "setup-message";
setupMessage.style.cssText = `
background: #ff9800;
color: white;
padding: 1em;
border-radius: 8px;
margin-bottom: 1em;
text-align: center;
`;
setupMessage.innerHTML = `
<h3 style="margin: 0 0 0.5em 0;">Welcome to PhotoMapAI!</h3>
<p style="margin: 0;">
To get started, please add your first image album below.
You'll need to specify the name and directory paths containing your images.
</p>
`;
return setupMessage;
}
removeSetupMessage() {
const setupMessage = this.overlay.querySelector(".setup-message");
if (setupMessage) {
setupMessage.remove();
}
}
showIndexingCompletedUI(cardElement) {
const cancelBtn = cardElement.querySelector(".cancel-index-btn");
const updateBtn = cardElement.querySelector(".create-index-btn");
const progressContainer = cardElement.querySelector(".progress-container");
// Hide the Cancel button and the progress indicator
cancelBtn.style.display = "none";
progressContainer.style.display = "none";
// Show the Update Index button
updateBtn.style.display = "inline-block";
}
createCompletionMessage() {
const completionMessage = document.createElement("div");
completionMessage.className = "completion-message";
completionMessage.style.cssText = `
background: #4caf50;
color: white;
padding: 1em;
border-radius: 8px;
margin-bottom: 1em;
text-align: center;
`;
completionMessage.innerHTML = `
<h4 style="margin: 0 0 0.5em 0;">Setup In Progress!</h4>
<p style="margin: 0;">
Your album "${state.album}" is being indexed.
Once indexing completes, this window will close and the semantic map will display.
</p>
`;
return completionMessage;
}
showCompletionMessage() {
// Remove any existing completion message before adding a new one
const existingCompletion = this.overlay.querySelector(".completion-message");
if (existingCompletion && existingCompletion.parentNode) {
existingCompletion.remove();
}
const completionMessage = this.createCompletionMessage();
if (this.elements.albumManagementContent) {
this.elements.albumManagementContent.insertBefore(
completionMessage,
this.elements.albumManagementContent.firstChild
);
}
return completionMessage;
}
async setupModeIndexingInProgress() {
this.removeSetupMessage();
this.showCompletionMessage();
}
async completeSetupMode() {
console.log("Exiting setup mode - indexing completed.");
this.enableClosing();
this.removeSetupMessage();
// Remove any existing completion message
const existingCompletion = this.overlay.querySelector(".completion-message");
if (existingCompletion && existingCompletion.parentNode) {
existingCompletion.remove();
}
}
// Closing control
disableClosing() {
const closeBtn = this.overlay.querySelector(".close-albums-btn");
if (closeBtn) {
closeBtn.style.display = "none";
}
this.overlay.onclick = null;
}
enableClosing() {
const closeBtn = this.overlay.querySelector(".close-albums-btn");
if (closeBtn) {
closeBtn.style.display = "block";
}
this.overlay.addEventListener("click", (e) => {
if (e.target === this.overlay) {
this.hide();
}
});
}
// Album management
async loadAlbums() {
try {
const albums = await this.fetchAvailableAlbums();
this.albumsList.innerHTML = "";
albums.forEach((album) => {
this.createAlbumCard(album);
});
} catch (error) {
console.error("Failed to load albums:", error);
}
}
createAlbumCard(album) {
const card = this.template.content.cloneNode(true);
// Populate album info with defensive handling
card.querySelector(".album-name").textContent = album.name || "Unknown Album";
card.querySelector(".album-key").textContent = `Key: ${album.key || "Unknown"}`;
card.querySelector(".album-description").textContent = album.description || "No description";
const imagePaths = album.image_paths || [];
card.querySelector(".album-paths").textContent = `Paths: ${imagePaths.join(", ") || "No paths configured"}`;
// Set up event listeners
const cardElement = card.querySelector(".album-card");
cardElement.dataset.albumKey = album.key;
this.attachCardEventListeners(card, cardElement, album);
this.albumsList.appendChild(card);
this.updateAlbumCardIndexStatus(cardElement, album);
}
async updateAlbumCardIndexStatus(cardElement, album) {
const status = cardElement.querySelector(".index-status");
const createBtn = cardElement.querySelector(".create-index-btn");
try {
const metadata = await getIndexMetadata(album.key);
if (metadata) {
const modDate = new Date(metadata.last_modified * 1000).toLocaleString(undefined, {
dateStyle: "medium",
timeStyle: "short",
});
const fileCount = metadata.filename_count;
status.textContent = `Index updated ${modDate} (${fileCount} images)`;
status.style.color = "green";
createBtn.textContent = "Update Index";
} else {
status.textContent = "No index present";
status.style.color = "red";
createBtn.textContent = "Create Index";
}
} catch {
status.textContent = "No index present";
status.style.color = "red";
createBtn.textContent = "Create Index";
}
}
attachCardEventListeners(card, cardElement, album) {
// Edit button
card.querySelector(".edit-album-btn").addEventListener("click", () => {
this.editAlbum(cardElement, album);
});
// Delete button
card.querySelector(".delete-album-btn").addEventListener("click", () => {
this.deleteAlbum(album.key);
});
// Index button
card.querySelector(".create-index-btn").addEventListener("click", () => {
this.startIndexing(album.key, cardElement);
});
// Cancel index button
card.querySelector(".cancel-index-btn").addEventListener("click", () => {
this.cancelIndexing(album.key, cardElement);
});
}
async addAlbum() {
const formData = this.getNewAlbumFormData();
// Map field names to their corresponding elements
const requiredFields = [
{ value: formData.key, element: this.elements.newAlbumKey },
{ value: formData.name, element: this.elements.newAlbumName },
{
value: formData.paths.length > 0 ? "has paths" : "",
element: this.elements.newAlbumPathsContainer,
},
];
let hasError = false;
// Remove previous error highlights and check for missing fields
requiredFields.forEach(({ value, element }) => {
element.classList.remove("input-error");
if (!value) {
element.classList.add("input-error");
hasError = true;
}
});
if (hasError) {
alert("Please fill in all required fields");
return;
}
// Check for duplicate album key
const albums = await this.fetchAvailableAlbums();
const duplicate = albums.some((album) => album.key === formData.key);
if (duplicate) {
this.elements.newAlbumKey.classList.add("input-error");
alert(`An album with the key "${formData.key}" already exists. Please choose a different key.`);
return;
}
// Use the collected paths directly
const paths = formData.paths;
// Always set index path based on first path
const indexPath = paths.length > 0 ? `${paths[0]}/photomap_index/embeddings.npz` : "";
const newAlbum = {
key: formData.key,
name: formData.name,
image_paths: paths,
index: indexPath,
umap_eps: 0.1,
description: formData.description,
};
try {
const response = await fetch("add_album/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newAlbum),
});
if (response.ok) {
await this.handleSuccessfulAlbumAdd(formData.key);
} else {
alert(`Failed to add album: ${response.statusText}`);
}
} catch (error) {
console.error("Failed to add album:", error);
alert("Failed to add album");
}
}
async handleSuccessfulAlbumAdd(albumKey) {
this.hideAddAlbumForm();
await this.loadAlbums();
// Set state.album directly to avoid triggering slideshow before indexing
if (state.album === null) {
state.album = albumKey;
}
await this.startAutoIndexing(albumKey);
if (this.isSetupMode) {
await this.setupModeIndexingInProgress();
// force reindexing
this.send_update_index_event(albumKey);
}
}
send_update_index_event(albumKey = state.album) {
window.dispatchEvent(
new CustomEvent("albumIndexError", {
detail: { albumKey, errorType: "outOfDate" },
})
);
}
async startAutoIndexing(albumKey) {
const albumCard = Array.from(this.albumsList.querySelectorAll(".album-card")).find(
(card) => card.dataset.albumKey === albumKey
);
if (albumCard) {
// Don't start indexing again - it's already running
// Just show the progress UI and let the existing polling handle updates
setTimeout(() => {
this.showProgressUI(albumCard); // This will scroll into view
}, AlbumManager.AUTO_INDEXING_DELAY);
}
}
async deleteAlbum(albumKey) {
if (!confirm(`Are you sure you want to delete album "${albumKey}"? This action cannot be undone.`)) {
return;
}
try {
const response = await fetch(`delete_album/${albumKey}`, {
method: "DELETE",
headers: { "Content-Type": "application/json" },
});
if (response.ok) {
const isCurrentAlbum = state.album === albumKey;
await this.refreshAlbumsAndDropdown();
if (isCurrentAlbum) {
await this.handleDeletedCurrentAlbum();
}
} else {
alert("Failed to delete album");
}
} catch (error) {
console.error("Failed to delete album:", error);
alert("Failed to delete album");
}
}
async handleDeletedCurrentAlbum() {
try {
const albums = await this.fetchAvailableAlbums();
if (albums.length > 0) {
const firstAlbum = albums[0];
console.log(`Switching from deleted album to: ${firstAlbum.key}`);
await this.updateCurrentAlbum(firstAlbum);
// Clear and reset slideshow (specific to deletion)
exitSearchMode();
this.single_swiper.removeSlidesAfterCurrent();
this.showAlbumSwitchNotification(firstAlbum.name);
} else {
console.warn("No albums available after deletion");
alert("No albums available. Please add a new album.");
}
} catch (error) {
console.error("Failed to handle deleted current album:", error);
}
}
// Edit functionality
editAlbum(cardElement, album) {
const editForm = cardElement.querySelector(".edit-form");
const albumInfo = cardElement.querySelector(".album-info");
// Remove 'editing' class from all cards first
document.querySelectorAll(".album-card.editing").forEach((card) => {
card.classList.remove("editing");
});
// Add 'editing' class to this card
cardElement.classList.add("editing");
// Set the edit form title to include the album name
const editTitle = editForm.querySelector(".edit-album-title");
if (editTitle) {
editTitle.innerHTML = `Editing Album <i>${album.name || "</i>"}`;
}
// Populate edit form
editForm.querySelector(".edit-album-name").value = album.name;
editForm.querySelector(".edit-album-description").value = album.description || "";
// Initialize the dynamic path fields for THIS specific card
this.initializePathFields(album.image_paths || [], cardElement);
// Show edit form
albumInfo.style.display = "none";
editForm.style.display = "block";
// Attach event listeners
editForm.querySelector(".save-album-btn").onclick = () => {
this.saveAlbumChanges(cardElement, album);
cardElement.classList.remove("editing");
};
editForm.querySelector(".cancel-edit-btn").onclick = () => {
albumInfo.style.display = "block";
editForm.style.display = "none";
cardElement.classList.remove("editing");
};
// --- Scroll the card so its bottom is visible ---
cardElement.scrollIntoView({ behavior: "smooth", block: "end" });
}
// Path field methods
createPathField(path = "", cardElement) {
const container = cardElement.querySelector(".edit-album-paths-container");
return this._createAlbumPathRow({
path,
container,
onAddRow: () => this.addPathField("", cardElement),
onRemoveRow: () => {
if (container && container.children.length === 0) {
this.addPathField("", cardElement);
}
},
onFolderPick: (currentPath, setPath) => {
createSimpleDirectoryPicker(
(selectedPath) => {
setPath(selectedPath);
},
currentPath,
{ showCreateFolder: true }
);
},
});
}
addPathField(path = "", cardElement) {
const container = cardElement.querySelector(".edit-album-paths-container");
if (container) {
const row = this.createPathField(path, cardElement);
container.appendChild(row);
}
}
initializePathFields(paths, cardElement) {
const container = cardElement.querySelector(".edit-album-paths-container");
if (container) {
container.innerHTML = "";
// Add existing paths
if (paths && paths.length > 0) {
paths.forEach((path) => this.addPathField(path, cardElement));
}
// Always ensure there's at least one empty field at the end
this.addPathField("", cardElement);
}
}
collectPathFields(cardElement) {
const inputs = cardElement.querySelectorAll(".edit-album-paths-container .album-path-input");
return Array.from(inputs)
.map((input) => input.value.trim())
.filter((path) => path.length > 0);
}
async saveAlbumChanges(cardElement, album) {
const editForm = cardElement.querySelector(".edit-form");
// Collect paths from dynamic fields for THIS specific card
const updatedPaths = this.collectPathFields(cardElement);
// Always set index path based on first path
const indexPath = updatedPaths.length > 0 ? `${updatedPaths[0]}/photomap_index/embeddings.npz` : "";
const updatedAlbum = {
key: album.key,
name: editForm.querySelector(".edit-album-name").value,
description: editForm.querySelector(".edit-album-description").value,
image_paths: updatedPaths,
index: indexPath,
};
// Compare old and new paths (order and content)
const oldPaths = Array.isArray(album.image_paths) ? album.image_paths : [];
const pathsChanged = oldPaths.length !== updatedPaths.length || oldPaths.some((p, i) => p !== updatedPaths[i]);
try {
const response = await fetch("update_album/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updatedAlbum),
});
if (response.ok) {
await this.refreshAlbumsAndDropdown();
// --- Begin new code ---
if (pathsChanged) {
this.send_update_index_event(updatedAlbum.key);
}
// --- End new code ---
} else {
alert("Failed to update album");
}
} catch (error) {
console.error("Failed to update album:", error);
alert("Failed to update album");
}
}
// Indexing functionality
async startIndexing(albumKey, cardElement, isCorrupted = false) {
// Prevent duplicate indexing requests (local guard)
if (this.progressPollers.has(albumKey)) {
console.log(`Indexing already in progress for album: ${albumKey}`);
return;
}
// Provide immediate feedback while the indexing request is being processed
const createBtn = cardElement.querySelector(".create-index-btn");
const originalBtnText = createBtn.textContent;
createBtn.textContent = "Update Pending...";
createBtn.disabled = true;
// Backend guard: check if indexing is already running
try {
const response = await fetch(`index_progress/${albumKey}`);
if (response.ok) {
const progress = await response.json();
if (progress.status === "indexing" || progress.status === "scanning" || progress.status === "mapping") {
console.log(`Backend reports indexing already in progress for album: ${albumKey}`);
this.showProgressUIWithoutScroll(cardElement, progress);
this.startProgressPolling(albumKey, cardElement);
return;
}
}
} catch {
console.debug(`Could not check backend indexing status for album: ${albumKey}`);
}