MediaWiki

MediaWiki:Common.js

From Illustrations in German Translations of Mark Twain's Works

Revision as of 17:39, 8 July 2025 by HMHTEST (talk | contribs)

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/* Any JavaScript here will be loaded for all users on every page load. */

/*AUSKLAPPMENÜS*/
$(function () {
  $('.ausklapp-button').click(function () {
    var $button = $(this);
    var $content = $button.next('.ausklapp-inhalt');

    $content.slideToggle(200);
    var expanded = $button.attr('aria-expanded') === 'true';
    $button.attr('aria-expanded', !expanded);
  });
});



/* Data Tables */
console.log('DataTables-Skript wird geladen...');

// DataTables JS nachladen und dann initialisieren
mw.loader.getScript('https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js')
.then(function() {
    console.log('DataTables erfolgreich geladen! Initialisiere Tabelle...');
    $(document).ready(function() {
        $('#catalog').DataTable({
            paging: true,
            pageLength: 100,
            searching: true,
            ordering: true,
            lengthMenu: [ [10, 25, 50, 100, 200, 600], [10, 25, 50, 100, 200, 600] ],
            order: [[1, 'asc']],
            language: {
                search: "Suche:",
                lengthMenu: "Show _MENU_ Entries",
                zeroRecords: "No Matches",
                info: "Page _PAGE_ of _PAGES_",
                infoEmpty: "Empty",
                infoFiltered: "(out of _MAX_ total entries)"
            },
            initComplete: function () {
                // Fügt für jede Spalte ein Suchfeld hinzu
                this.api().columns().every(function () {
                    var column = this;
                    var header = $(column.header());
                    var columnTitle = header.text(); // Spaltentitel extrahieren
                    var input = $('<input type="text" placeholder="' + columnTitle + ' ..." style="width: 100%; padding: 5px;"/>')
                        .appendTo($(header).empty())  // Leert die Headerzelle und fügt das Eingabefeld ein
                        .on('keyup change', function () {
                            column.search(this.value).draw();  // Filtert die Spalte nach Eingabewerten
                        })
                        .on('click', function(e) {
                            e.stopPropagation(); // Verhindert, dass der Klick die Sortierung beeinflusst
                        });
                });
            }
        });
    });
})
.catch(function(err) {
    console.error('Fehler beim Laden von DataTables:', err);
});

// Hover-Preview für Bild-Links in DataTables
$(document).ready(function() {
    // Neuen Image-Container einfügen
    $('body').append('<div id="image-hover-preview" style="display:none; position:absolute; z-index:9999;"><img src="" style="max-width:400px; max-height:400px; border:1px solid #ccc; background:white; padding:5px;"></div>');

    // Auf alle Links in der Tabelle achten
    $('#catalog').on('mouseenter', 'a', function(e) {
        var href = $(this).attr('href');
        if (href && href.includes('/Special:Redirect/file/')) {
            var imgUrl = href; // URL direkt verwenden
            $('#image-hover-preview img').attr('src', imgUrl);
            $('#image-hover-preview').show();
        }
    }).on('mousemove', 'a', function(e) {
        $('#image-hover-preview').css({
            top: e.pageY + 20 + 'px',
            left: e.pageX + 20 + 'px'
        });
    }).on('mouseleave', 'a', function() {
        $('#image-hover-preview').hide();
    });
});

document.getElementById('searchButton').addEventListener('click', function() {
    var tags = document.getElementById('tagInput').value.split(',').map(tag => tag.trim());
    searchImagesByTags(tags);
});

document.getElementById('searchButton').addEventListener('click', function() {
    var tags = document.getElementById('tagInput').value.split(',').map(tag => tag.trim());
    searchImagesByTags(tags);
});

function searchImagesByTags(tags) {
    var url = new URL(window.location.href);
    var apiUrl = url.origin + '/w/api.php';
    
    // Hier wird eine Anfrage an die MediaWiki API gestellt, um nach Bildern zu suchen, die den Tags entsprechen
    fetch(`${apiUrl}?action=query&format=json&list=categorymembers&cmtitle=Category:${tags.join('&cmtitle=Category:')}&cmtype=file`)
        .then(response => response.json())
        .then(data => {
            var images = data.query.categorymembers;
            displayImages(images);
        })
        .catch(error => console.error('Error:', error));
}

function displayImages(images) {
    var galleryContainer = document.getElementById('galleryContainer');
    galleryContainer.innerHTML = ''; // Leere den Container, um Platz für neue Bilder zu schaffen

    // Überprüfe, ob Bilder vorhanden sind
    if (images.length === 0) {
        galleryContainer.innerHTML = '<p>Keine Bilder mit den angegebenen Tags gefunden.</p>';
        return;
    }

    // Bilder in die Galerie einfügen
    images.forEach(image => {
        var imgElement = document.createElement('img');
        imgElement.src = '/index.php/Special:Redirect/file/' + image.title.replace('Category:', '');
        imgElement.alt = image.title;
        galleryContainer.appendChild(imgElement);
    });
}
// Funktion zur Extraktion der Dateinamen aus der Tabelle und zur Anzeige in der Galerie
function updateGalleryFromTable() {
    // Tabelle durchsuchen und Dateinamen extrahieren
    var rows = document.querySelectorAll('#catalog tbody tr');
    var imageLinks = [];

    rows.forEach(row => {
        var imageCell = row.cells[8];  // Die 9. Zelle enthält den Dateinamen als Link
        var link = imageCell.querySelector('a');  // Link innerhalb der Zelle
        if (link) {
            var imageName = link.textContent.trim();  // Der Text des Links ist der Dateiname
            var imageUrl = '/index.php/Special:Redirect/file/' + imageName + '.jpg';
            imageLinks.push(imageUrl);
        }
    });

    // Neue Seite mit Galerie öffnen
    var galleryWindow = window.open('', '_blank');
    if (galleryWindow) {
        galleryWindow.document.write('<html><head><title>Gallery</title>');
        galleryWindow.document.write('<style>');
        galleryWindow.document.write('body { font-family: sans-serif; padding: 20px; }');
        galleryWindow.document.write('img { max-width: 300px; margin: 10px; cursor: pointer; display: inline-block; }');
        galleryWindow.document.write('</style></head><body>');
        galleryWindow.document.write('<h2>Results</h2>');

        imageLinks.forEach(url => {
            galleryWindow.document.write('<img src="' + url + '" onclick="window.open(\'' + url + '\')">');
        });

        galleryWindow.document.write('</body></html>');
        galleryWindow.document.close();
    } else {
        alert('Popup wurde blockiert. Bitte erlaube Popups für diese Seite.');
    }
}

$(document).ready(function () {
    const columnCount = 9;

    // Neue Bedingung hinzufügen
    $('#addCondition').on('click', function () {
        const newRow = $('<div class="search-row" style="margin-bottom: 5px;">' +
            '<select class="bool-select">' +
                '<option value="AND">AND</option>' +
                '<option value="OR">OR</option>' +
                '<option value="NOT">NOT</option>' +
                '<option value="XOR">XOR</option>' +
            '</select>' +
            '<select class="field-select">' +
                '<option value="8">ID</option>' +
                '<option value="all">All</option>' +
                '<option value="0">Book</option>' +
                '<option value="1">Year</option>' +
                '<option value="2">Illustrator</option>' +
                '<option value="3">Chpt in Orig</option>' +
                '<option value="4">Chpt in this Ed.</option>' +
                '<option value="5">Ill. in Chpt.</option>' +
                '<option value="6">Illustration Title</option>' +
                '<option value="7">Tags</option>' +
            '</select>' +
            '<input type="text" class="search-input" placeholder=" ">' +
            '<button class="remove-condition" style="margin-left: 5px;">🗑️</button>' +
        '</div>');
        $('#searchConditions').append(newRow);
    });

    // Dynamisch hinzugefügte Bedingungen löschen
    $('#searchConditions').on('click', '.remove-condition', function () {
        if ($('#searchConditions .search-row').not('.fixed').length > 1) {
            $(this).closest('.search-row').remove();
        }
    });

    // Suche ausführen
    $('#runAdvancedSearch').on('click', function () {
        const table = $('#catalog').DataTable();
        table.search('').columns().search('');

        const filters = [];

        // 1. Feste erste Bedingung einfügen
        filters.push({
            column: '8', // ID-Spalte
            term: 'hf',
            boolOp: null
        });

        // 2. Alle weiteren Bedingungen
        $('#searchConditions .search-row').not('.fixed').each(function () {
            const column = $(this).find('.field-select').val();
            const term = $(this).find('.search-input').val().trim();
            const boolOp = $(this).find('.bool-select').val();

            if (term !== '') {
                filters.push({ column, term, boolOp });
            }
        });

        if (filters.length === 0) {
            table.draw();
            return;
        }

        // Filterlogik
        $.fn.dataTable.ext.search = [];
        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {
            let result = null;

            filters.forEach(function (filter, i) {
                const val = filter.column === 'all'
                    ? data.join(' ').toLowerCase()
                    : (data[filter.column] || '').toLowerCase();

                const match = val.includes(filter.term.toLowerCase());

                if (i === 0) {
                    result = match;
                } else {
                    switch (filter.boolOp) {
                        case 'AND': result = result && match; break;
                        case 'OR':  result = result || match; break;
                        case 'NOT': result = result && !match; break;
                        case 'XOR': result = (result && !match) || (!result && match); break;
                    }
                }
            });

            return result;
        });

        table.draw();
    });
});