Jump to content

User:Polygnotus/Scripts/SectionLinks.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Add link icons with tooltips to h2 headers for current versions, old revisions, and diffs
(function() {
    function addLinkIcons() {
        const headers = document.querySelectorAll('h2[id]');
        
        headers.forEach(header => {
            // Skip the table of contents heading
            if (header.id === 'mw-toc-heading') {
                return;
            }

            const isCurrentVersion = !window.location.search.match(/[?&]oldid=(\d+)/) && !document.querySelector('.diff-currentversion-title');
            
            if (isCurrentVersion) {
                // Add two icons for current version
                addIcon(header, '🔗', false, 'Copy link to this section'); // Chain link emoji for section link
                addIcon(header, '📌', true, 'Copy permalink to this section');  // Pushpin emoji for permalink
            } else {
                // Add single icon for old revision or diff
                addIcon(header, '🔗', true, 'Copy link to this section of this specific revision');
            }
        });
    }

    function addIcon(header, iconText, isPermalink, tooltipText) {
        const icon = document.createElement('span');
        icon.innerHTML = iconText;
        icon.style.cursor = 'pointer';
        icon.style.marginRight = '5px';
        icon.style.fontSize = '0.8em';
        icon.title = tooltipText; // Add tooltip
        
        icon.addEventListener('click', function(e) {
            e.preventDefault();
            let url;
            
            if (isPermalink) {
                const currentId = mw.config.get('wgRevisionId');
                url = `${window.location.origin}${window.location.pathname}?oldid=${currentId}#${header.id}`;
            } else {
                url = `${window.location.origin}${window.location.pathname}#${header.id}`;
            }
            
            navigator.clipboard.writeText(url).then(() => {
                mw.notify(`${isPermalink ? 'Permalink' : 'Section link'} copied to clipboard!`, {
                    type: 'success',
                    tag: 'urlCopy'
                });
            }).catch(() => {
                mw.notify('Failed to copy URL', {
                    type: 'error',
                    tag: 'urlCopy'
                });
            });
        });
        
        header.insertBefore(icon, header.firstChild);
    }

    // Run the function when the DOM is fully loaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', addLinkIcons);
    } else {
        addLinkIcons();
    }
})();