User:Polygnotus/Scripts/Fragment.js

// <nowiki>
// Add "Link to selected text" to Tools menu
$(function() {
    mw.util.addPortletLink(
        'p-tb',
        '#',
        'Link to selected text',
        't-linktotext',
        'Create a URL fragment linking to the selected text'
    );
    
    $('#t-linktotext').on('click', function(e) {
        e.preventDefault();
        
        var selection = window.getSelection();
        
        if (!selection || selection.rangeCount === 0 || selection.toString().trim() === '') {
            mw.notify('No text selected', { type: 'error' });
            return;
        }
        
        var range = selection.getRangeAt(0);
        
        // Get the selected text
        var selectedText = selection.toString().replace(/\s+/g, ' ').trim();
        
        // Get text before selection for prefix
        var beforeRange = range.cloneRange();
        beforeRange.collapse(true);
        beforeRange.setStart(beforeRange.startContainer.parentElement || beforeRange.startContainer, 0);
        var beforeText = beforeRange.toString().replace(/\s+/g, ' ').trim();
        
        // Get text after selection for suffix
        var afterRange = range.cloneRange();
        afterRange.collapse(false);
        var endContainer = range.endContainer;
        var endParent = endContainer.parentElement || endContainer;
        afterRange.setEndAfter(endParent);
        var afterText = afterRange.toString().replace(/\s+/g, ' ').trim();
        
        // Extract prefix (last few words before selection)
        var beforeWords = beforeText.split(' ').filter(w => w.length > 0);
        var prefix = beforeWords.slice(-3).join(' ');
        
        // Extract suffix (first few words after selection)
        var afterWords = afterText.split(' ').filter(w => w.length > 0);
        var suffix = afterWords.slice(0, 3).join(' ');
        
        // Build text fragment
        var words = selectedText.split(' ').filter(w => w.length > 0);
        var textFragment = '';
        
        if (prefix) {
            textFragment += encodeURIComponent(prefix) + '-,';
        }
        
        if (words.length > 5) {
            var textStart = words.slice(0, 3).join(' ');
            var textEnd = words.slice(-3).join(' ');
            textFragment += encodeURIComponent(textStart) + ',' + encodeURIComponent(textEnd);
        } else {
            textFragment += encodeURIComponent(selectedText);
        }
        
        if (suffix) {
            textFragment += ',-' + encodeURIComponent(suffix);
        }
        
        // Store fragment and reload with a flag
        sessionStorage.setItem('pendingTextFragment', textFragment);
        var reloadUrl = window.location.origin + window.location.pathname + 
                       window.location.search + (window.location.search ? '&' : '?') + '_clearhighlight=1';
        window.location.href = reloadUrl;
    });
    
    // On page load, check if we're coming back from a reload
    var urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('_clearhighlight')) {
        var textFragment = sessionStorage.getItem('pendingTextFragment');
        if (textFragment) {
            sessionStorage.removeItem('pendingTextFragment');
            // Remove the flag from URL and add text fragment
            urlParams.delete('_clearhighlight');
            var cleanSearch = urlParams.toString();
            var newUrl = window.location.origin + window.location.pathname + 
                        (cleanSearch ? '?' + cleanSearch : '') + '#:~:text=' + textFragment;
            window.location.replace(newUrl);
        }
    }
});
// </nowiki>

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.