User:RoyZuo/CopyFilename.js

// Add a copy icon button before every filename
// © 2025 [[User:RoyZuo]]
// Feedback ☞ [[c:User talk:RoyZuo]]
mw.hook('wikipage.content').add(function($content) {
    $content.find("li.gallerybox").each(function() {
        let $galleryTextDiv = $(this).find("div.gallerytext");
        if (!$galleryTextDiv.length) return; // Skip if no gallerytext div

        let $fileLink = $galleryTextDiv.find("a.galleryfilename");
        if (!$fileLink.length) return; // Skip if no file link

        // Avoid adding duplicate buttons
        if ($galleryTextDiv.find(".copy-button").length) return;

        // Create the copy button (icon)
        let $copyButton = $('<button class="copy-button" style="border: none; background: transparent; cursor: pointer; margin-right: 5px; padding: 2px; display: inline-flex; align-items: center;">' +
            '⧉' + '</button>');

        // Copy function
        $copyButton.on("click", function() {
            // Add "File:" prefix before the filename text
            let filenameWithPrefix = "File:" + $fileLink.text().trim();
            navigator.clipboard.writeText(filenameWithPrefix).then(() => {
                $copyButton.html("✅"); // Change to ✅ on success
                setTimeout(() => {
                    $copyButton.html('⧉'); // Revert back after 3 seconds
                }, 3000);
            });
        });

        // Insert the button before the filename inside .gallerytext
        $fileLink.before($copyButton);
    });
});