Spaces:
Runtime error
Runtime error
File size: 25,181 Bytes
1e7308f |
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 |
// 1. Logger-Klasse
class Logger {
static isDebugMode = false;
static debug(message, data = null) {
if (this.isDebugMode) {
console.log(`[Debug] ${message}`, data || '');
}
}
static error(message, error = null) {
console.error(`[Error] ${message}`, error || '');
}
static initializeDebugMode() {
try {
const urlParams = new URLSearchParams(window.location.search);
this.isDebugMode = urlParams.has('debug');
} catch (error) {
console.error('Fehler beim Initialisieren des Debug-Modus:', error);
this.isDebugMode = false;
}
}
}
// 2. Utils
const utils = {
showLoading() {
if (document.body) {
document.body.classList.add('loading');
Logger.debug('Loading-Status aktiviert');
} else {
Logger.error('document.body nicht verfügbar');
}
},
hideLoading() {
if (document.body) {
document.body.classList.remove('loading');
Logger.debug('Loading-Status deaktiviert');
} else {
Logger.error('document.body nicht verfügbar');
}
},
safeGetElement(id) {
const element = document.getElementById(id);
if (!element) {
Logger.error(`Element mit ID '${id}' nicht gefunden`);
return null;
}
return element;
},
async withLoading(asyncFn) {
try {
this.showLoading();
await asyncFn();
} finally {
this.hideLoading();
}
}
};
// In der ImageModal-Klasse:
class ImageModal {
constructor() {
this.modal = null;
this.modalImg = null;
this.currentImageIndex = 0;
this.selectedImages = [];
this.initialize();
}
initialize() {
if (typeof bootstrap === 'undefined') {
Logger.error('Bootstrap ist nicht verfügbar');
return;
}
const modalElement = utils.safeGetElement('imageModal');
if (!modalElement) return;
this.modal = new bootstrap.Modal(modalElement);
this.modalImg = utils.safeGetElement('modalImage');
// Event-Listener für Modal-Schließen
modalElement.addEventListener('hidden.bs.modal', () => {
this.cleanupModal();
});
// Klick-Handler für Modal-Container
const imageContainer = document.querySelector('.image-container');
if (imageContainer && this.modalImg) {
imageContainer.addEventListener('click', (e) => {
if (e.target === this.modalImg) {
this.hide();
}
});
}
// Event-Listener für Tastendruck (Pfeiltasten)
document.addEventListener('keydown', (event) => {
if (this.modal && this.modal._isShown) { // Modal muss geöffnet sein
if (event.key === 'ArrowLeft') {
event.stopPropagation(); // Verhindere Standardverhalten und Bubbling
this.showPreviousImage();
} else if (event.key === 'ArrowRight') {
event.stopPropagation(); // Verhindere Standardverhalten und Bubbling
this.showNextImage();
}
}
});
// Download-Button Handler
const downloadBtn = utils.safeGetElement('modalDownloadBtn');
if (downloadBtn) {
downloadBtn.addEventListener('click', async () => {
const filename = this.modalImg?.dataset?.filename;
if (filename) {
await this.downloadImage(filename);
} else {
Logger.error('Kein Dateiname für Download verfügbar');
}
});
}
}
async downloadImage(filename) {
await utils.withLoading(async () => {
try {
const response = await fetch(`/flux-pics/${filename}`); // Direkt über StaticFiles
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
Logger.error('Download-Fehler:', error);
alert('Ein Fehler ist beim Download aufgetreten: ' + error.message);
}
});
}
open(img, selectedImages = []) {
if (!this.modal || !this.modalImg) {
Logger.error('Modal nicht korrekt initialisiert');
return;
}
Logger.debug('Öffne Bild-Modal', img);
// Setze die ausgewählten Bilder und den Index des aktuellen Bildes
this.selectedImages = selectedImages;
this.currentImageIndex = this.selectedImages.indexOf(img.dataset.filename);
this.modalImg.src = img.src;
this.modalImg.dataset.filename = img.dataset.filename;
const metadataFields = ['format', 'timestamp', 'album', 'category', 'prompt', 'optimized_prompt'];
metadataFields.forEach(field => {
const element = utils.safeGetElement(`modal${field.charAt(0).toUpperCase() + field.slice(1)}`);
if (element) {
element.textContent = img.dataset[field] || 'Nicht verfügbar';
}
});
// Füge einen Event-Listener hinzu, um den Fokus auf das Modal zu setzen,
// nachdem es vollständig angezeigt wurde (shown.bs.modal)
this.modal._element.addEventListener('shown.bs.modal', () => {
this.modal._element.focus();
});
this.modal.show();
}
hide() {
this.modal?.hide();
}
cleanupModal() {
document.body.classList.remove('modal-open');
const backdrop = document.querySelector('.modal-backdrop');
if (backdrop) {
backdrop.remove();
}
document.body.style.overflow = '';
document.body.style.paddingRight = '';
}
showPreviousImage() {
if (this.currentImageIndex > 0) {
this.currentImageIndex--;
this.updateModalImage();
}
}
showNextImage() {
if (this.currentImageIndex < this.selectedImages.length - 1) {
this.currentImageIndex++;
this.updateModalImage();
}
}
updateModalImage() {
const filename = this.selectedImages[this.currentImageIndex];
const imgElement = document.querySelector(`.image-thumbnail[data-filename="${filename}"]`);
if (imgElement) {
this.modalImg.src = imgElement.src;
this.modalImg.dataset.filename = filename;
// Metadaten aktualisieren
const metadataFields = ['format', 'timestamp', 'album', 'category', 'prompt', 'optimized_prompt'];
metadataFields.forEach(field => {
const element = utils.safeGetElement(`modal${field.charAt(0).toUpperCase() + field.slice(1)}`);
if (element) {
element.textContent = imgElement.dataset[field] || 'Nicht verfügbar';
}
});
} else {
Logger.error('Bild-Element für Dateiname nicht gefunden:', filename);
}
}
}
class GalleryManager {
constructor() {
this.selectedImages = new Set();
this.imageModal = new ImageModal();
this.initialize();
}
initialize() {
this.initializeSelectionHandling();
this.initializeGalleryViews();
this.initializeDownloadHandling();
}
initializeSelectionHandling() {
// "Alle auswählen" Funktionalität
const selectAllCheckbox = utils.safeGetElement('selectAll');
if (selectAllCheckbox) {
selectAllCheckbox.addEventListener('change', () => {
const itemCheckboxes = document.querySelectorAll('.select-item');
itemCheckboxes.forEach(checkbox => {
checkbox.checked = selectAllCheckbox.checked;
this.updateSelectedImages(checkbox);
});
});
}
// Einzelne Bildauswahl
document.querySelectorAll('.select-item').forEach(checkbox => {
checkbox.addEventListener('change', () => this.updateSelectedImages(checkbox));
});
}
updateSelectedImages(checkbox) {
const card = checkbox.closest('.card');
if (!card) return;
const img = card.querySelector('img');
if (!img || !img.dataset.filename) {
Logger.error('Ungültiges Bild-Element in der Karte');
return;
}
if (checkbox.checked) {
this.selectedImages.add(img.dataset.filename);
} else {
this.selectedImages.delete(img.dataset.filename);
}
Logger.debug(`Ausgewählte Bilder aktualisiert: ${this.selectedImages.size} Bilder`);
}
getSelectedImages() {
return Array.from(this.selectedImages);
}
initializeGalleryViews() {
// Thumbnail-Galerie
const thumbGalleryBtn = utils.safeGetElement('thumbgalleryBtn');
if (thumbGalleryBtn) {
thumbGalleryBtn.addEventListener('click', () => this.openThumbnailGallery());
}
// Grid Layout
const gridLayout = utils.safeGetElement('gridLayout');
if (gridLayout) {
gridLayout.addEventListener('change', () => this.updateGridLayout(gridLayout.value));
}
// Bild-Thumbnails
document.querySelectorAll('.image-thumbnail').forEach(img => {
img.addEventListener('click', () => this.imageModal.open(img));
});
}
async openThumbnailGallery() {
const selectedImages = this.getSelectedImages();
if (selectedImages.length === 0) {
alert('Keine Bilder ausgewählt.');
return;
}
const galleryModal = new bootstrap.Modal(utils.safeGetElement('thumbGalleryModal'));
const container = utils.safeGetElement('thumbGalleryContainer');
if (!container) return;
container.innerHTML = '';
selectedImages.forEach(filename => {
const thumbContainer = this.createThumbnailElement(filename);
if (thumbContainer) {
container.appendChild(thumbContainer);
}
});
galleryModal.show();
}
createThumbnailElement(filename) {
const container = document.createElement('div');
container.className = 'thumb-container m-2';
const img = document.createElement('img');
img.src = `/flux-pics/${filename}`;
img.className = 'img-thumbnail thumbnail-img';
img.dataset.filename = filename;
img.style.maxWidth = '150px';
img.style.cursor = 'pointer';
const downloadBtn = document.createElement('button');
downloadBtn.className = 'btn btn-sm btn-primary download-thumb';
downloadBtn.innerHTML = '<i class="fas fa-download"></i>';
// Event-Listener
img.addEventListener('click', () => this.imageModal.open(img));
downloadBtn.addEventListener('click', async () => {
await this.imageModal.downloadImage(filename);
});
container.appendChild(img);
container.appendChild(downloadBtn);
return container;
}
updateGridLayout(columns) {
const imageGrid = utils.safeGetElement('imageGrid');
if (imageGrid) {
const validColumns = Math.max(1, Math.min(6, parseInt(columns) || 3));
imageGrid.className = `row row-cols-1 row-cols-md-${validColumns}`;
Logger.debug(`Grid-Layout aktualisiert: ${validColumns} Spalten`);
}
}
initializeDownloadHandling() {
const downloadBtn = utils.safeGetElement('downloadSelected');
if (downloadBtn) {
downloadBtn.addEventListener('click', () => this.handleBulkDownload());
}
}
async handleBulkDownload() {
const selectedImages = this.getSelectedImages();
if (selectedImages.length === 0) {
alert('Keine Bilder ausgewählt.');
return;
}
const useZip = selectedImages.length > 1 &&
confirm('Möchten Sie die Bilder als ZIP-Datei herunterladen?\nKlicken Sie "OK" für ZIP oder "Abbrechen" für Einzeldownloads.');
await utils.withLoading(async () => {
try {
if (useZip) {
await this.downloadAsZip(selectedImages);
} else {
await this.downloadIndividually(selectedImages);
}
/*alert('Download erfolgreich abgeschlossen.');*/
} catch (error) {
Logger.error('Bulk-Download Fehler:', error);
alert('Ein Fehler ist aufgetreten: ' + error.message);
}
});
}
async downloadAsZip(files) {
const response = await fetch('/flux-pics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ selectedImages: files })
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'images.zip';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
async downloadIndividually(files) {
for (const filename of files) {
await this.imageModal.downloadImage(filename);
// Kleine Pause zwischen Downloads
await new Promise(resolve => setTimeout(resolve, 500));
}
}
}
// Slideshow-Verwaltung
// In der SlideshowManager-Klasse:
class SlideshowManager {
constructor(gallery) {
if (!gallery) {
Logger.error('GalleryManager ist erforderlich');
throw new Error('GalleryManager ist erforderlich');
}
this.gallery = gallery;
this.slideInterval = 3000;
this.currentSlideIndex = 0;
this.slideshowInterval = null;
this.carousel = null;
this.slideshowModal = null;
// Initialisierung direkt im Konstruktor
const slideshowBtn = utils.safeGetElement('slideshowBtn');
if (slideshowBtn) {
slideshowBtn.addEventListener('click', () => this.openSlideshow());
}
}
async openSlideshow() {
const selectedImages = this.gallery.getSelectedImages();
if (selectedImages.length === 0) {
alert('Keine Bilder ausgewählt.');
return;
}
const modalElement = utils.safeGetElement('slideshowModal');
if (!modalElement) return;
this.slideshowModal = new bootstrap.Modal(modalElement);
const container = utils.safeGetElement('slideshowContainer');
if (!container) return;
container.innerHTML = '';
this.createSlides(container, selectedImages);
const carouselElement = utils.safeGetElement('carouselExampleControls');
if (carouselElement) {
this.carousel = new bootstrap.Carousel(carouselElement, {
interval: false
});
}
// Event-Listener für Modal-Schließen
modalElement.addEventListener('hidden.bs.modal', () => {
this.cleanupSlideshow();
});
this.setupSlideshowControls();
this.slideshowModal.show();
}
createSlides(container, images) {
images.forEach((filename, index) => {
const div = document.createElement('div');
div.classList.add('carousel-item');
if (index === 0) div.classList.add('active');
const img = document.createElement('img');
img.src = `/flux-pics/${filename}`;
img.classList.add('d-block', 'w-100');
img.dataset.filename = filename;
img.onerror = () => {
Logger.error(`Fehler beim Laden des Bildes: ${filename}`);
// Optional: Anstelle des Bildes ein Placeholder-Element anzeigen
const errorPlaceholder = document.createElement('div');
errorPlaceholder.classList.add('error-placeholder');
errorPlaceholder.textContent = `Fehler beim Laden des Bildes: ${filename}`;
div.replaceChild(errorPlaceholder, img);
};
div.appendChild(img);
container.appendChild(div);
});
}
setupSlideshowControls() {
const playBtn = utils.safeGetElement('playSlideshow');
const pauseBtn = utils.safeGetElement('pauseSlideshow');
if (playBtn && pauseBtn) {
playBtn.addEventListener('click', () => this.startSlideshow());
pauseBtn.addEventListener('click', () => this.pauseSlideshow());
}
const fullscreenBtn = utils.safeGetElement('fullscreenBtn');
if (fullscreenBtn) {
fullscreenBtn.addEventListener('click', () => this.toggleFullscreen());
}
const downloadBtn = utils.safeGetElement('downloadCurrentSlide');
if (downloadBtn) {
downloadBtn.addEventListener('click', () => this.downloadCurrentSlide());
}
}
startSlideshow() {
if (!this.carousel) return;
this.slideshowInterval = setInterval(() => {
this.carousel.next();
}, this.slideInterval);
const playBtn = utils.safeGetElement('playSlideshow');
const pauseBtn = utils.safeGetElement('pauseSlideshow');
if (playBtn && pauseBtn) {
playBtn.style.display = 'none';
pauseBtn.style.display = 'block';
}
}
pauseSlideshow() {
if (this.slideshowInterval) {
clearInterval(this.slideshowInterval);
this.slideshowInterval = null;
}
const playBtn = utils.safeGetElement('playSlideshow');
const pauseBtn = utils.safeGetElement('pauseSlideshow');
if (playBtn && pauseBtn) {
pauseBtn.style.display = 'none';
playBtn.style.display = 'block';
}
}
async toggleFullscreen() {
const modalElement = utils.safeGetElement('slideshowModal');
if (!modalElement) return;
try {
if (!document.fullscreenElement) {
if (modalElement.requestFullscreen) {
await modalElement.requestFullscreen();
} else if (modalElement.webkitRequestFullscreen) {
await modalElement.webkitRequestFullscreen();
} else if (modalElement.msRequestFullscreen) {
await modalElement.msRequestFullscreen();
}
} else {
if (document.exitFullscreen) {
await document.exitFullscreen();
}
}
} catch (error) {
Logger.error('Vollbild-Fehler:', error);
}
}
async downloadCurrentSlide() {
const activeSlide = document.querySelector('.carousel-item.active img');
if (activeSlide?.dataset?.filename) {
try {
const filename = activeSlide.dataset.filename;
const response = await fetch(`/flux-pics/${filename}`);
if (!response.ok) {
throw new Error(`Fehler beim Herunterladen des Bildes: ${response.status} ${response.statusText}`);
}
const blob = await response.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
} catch (error) {
Logger.error('Fehler beim Herunterladen des Bildes:', error);
}
} else {
Logger.error('Kein aktives Bild gefunden');
}
}
cleanupSlideshow() {
this.pauseSlideshow();
document.body.classList.remove('modal-open');
const backdrop = document.querySelector('.modal-backdrop');
if (backdrop) {
backdrop.remove();
}
document.body.style.overflow = '';
document.body.style.paddingRight = '';
if (document.fullscreenElement) {
document.exitFullscreen().catch(err => {
Logger.error('Fehler beim Beenden des Vollbildmodus:', err);
});
}
}
}
// 3. AppInitializer-Klasse
class AppInitializer {
constructor() {
this.gallery = null;
this.slideshow = null;
}
initialize() {
try {
Logger.initializeDebugMode();
document.addEventListener('DOMContentLoaded', () => {
try {
this.initializeComponents();
this.setupGlobalEventListeners();
Logger.debug('Anwendung erfolgreich initialisiert');
// >>> Ab hier Deine zusätzlichen Funktionen:
// -----------------------------------------------------
// 1) "Alles auswählen" (nur falls du es separat brauchst):
const selectAllCheckbox = document.getElementById('selectAll');
if (selectAllCheckbox) {
selectAllCheckbox.addEventListener('change', function() {
const checkboxes = document.querySelectorAll('.select-item');
checkboxes.forEach(cb => {
cb.checked = selectAllCheckbox.checked;
});
});
}
// 2) Items-per-page-Select: Bei Änderung URL manipulieren und Seite neuladen
const itemsPerPageSelect = document.getElementById('itemsPerPageSelect');
if (itemsPerPageSelect) {
itemsPerPageSelect.addEventListener('change', function() {
const newVal = this.value;
// Aktuelle URL analysieren
const url = new URL(window.location.href);
// items_per_page setzen
url.searchParams.set('items_per_page', newVal);
// Page zurücksetzen (falls "page" existiert)
url.searchParams.delete('page');
// Seite neuladen
window.location.href = url.toString();
});
}
// -----------------------------------------------------
// >>> Ende deiner zusätzlichen Funktionen
} catch (error) {
Logger.error('Fehler bei der Initialisierung:', error);
alert('Es gab ein Problem beim Laden der Anwendung. Bitte laden Sie die Seite neu.');
}
});
} catch (error) {
console.error('Kritischer Fehler bei der Initialisierung:', error);
}
}
initializeComponents() {
try {
this.gallery = new GalleryManager();
this.slideshow = new SlideshowManager(this.gallery);
Logger.debug('Komponenten initialisiert');
} catch (error) {
Logger.error('Fehler bei der Komponenten-Initialisierung:', error);
throw error;
}
}
setupGlobalEventListeners() {
try {
this.setupScrollToTop();
this.setupKeyboardNavigation();
Logger.debug('Globale Event-Listener eingerichtet');
} catch (error) {
Logger.error('Fehler beim Einrichten der Event-Listener:', error);
throw error;
}
}
setupScrollToTop() {
const scrollTopBtn = utils.safeGetElement('scrollTopBtn');
if (scrollTopBtn) {
window.addEventListener('scroll', () => {
scrollTopBtn.style.display = window.scrollY > 300 ? 'block' : 'none';
});
scrollTopBtn.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
}
}
setupKeyboardNavigation() {
document.addEventListener('keydown', (e) => this.handleKeyboardNavigation(e));
}
handleKeyboardNavigation(e) {
if (e.key === 'Escape') {
this.closeAllModals();
}
}
checkBootstrapAvailability() {
if (typeof bootstrap === 'undefined') {
Logger.error('Bootstrap ist nicht verfügbar');
return false;
}
return true;
}
}
// 4. Anwendung starten
try {
const app = new AppInitializer();
app.initialize();
} catch (error) {
console.error('Kritischer Fehler beim Erstellen der Anwendung:', error);
}
|