Utente:Tino/BibWiki.js

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca

Questa pagina definisce alcuni parametri di aspetto e comportamento generale di tutte le pagine. Per personalizzarli vedi Aiuto:Stile utente.


Nota: dopo aver salvato è necessario pulire la cache del proprio browser per vedere i cambiamenti (per le pagine globali è comunque necessario attendere qualche minuto). Per Mozilla / Firefox / Safari: fare clic su Ricarica tenendo premuto il tasto delle maiuscole, oppure premere Ctrl-F5 o Ctrl-R (Command-R su Mac); per Chrome: premere Ctrl-Shift-R (Command-Shift-R su un Mac); per Konqueror: premere il pulsante Ricarica o il tasto F5; per Opera può essere necessario svuotare completamente la cache dal menù Strumenti → Preferenze; per Internet Explorer: mantenere premuto il tasto Ctrl mentre si preme il pulsante Aggiorna o premere Ctrl-F5.

/*
 * Questo script cerca automaticamente una citazione in una bibliografia
 * personale dell'utente e la inserisce in loco. Per utilizzarlo, inserire
 * il testo
 * 
 *   {{cid:item
 * 
 * dove item è il cid dell'elemento bibliografico da inserire, quindi premere
 * lo shortcut con il cursore al termine di tale testo. La prima corrispondenza
 * trovata verrà inserita, e ripetendo la pressione dello shortcut si possono
 * scorrere le altre eventuali corrispondenza trovate.
 * 
 * Shortcut: ctrl + e
 * 
 * @author [[Utente:Tino]]
 */
(function(mw, $) {
    'use strict';
    
    // configuration vars
    var keyCode = 69; // e key
    var alt     = false;
    var shift   = false;
    var meta    = false;
    var ctrl    = true;
    
    // flag for default browser behaviour on the shortcut
    var keystrokeDefault = true;
    
    var inputArea = $('#wpTextbox1');
    
    // array of citations matching the cid
    var matches = null;
    // index of the current result inserted
    var index   = 0;
    // last cid pattern retrieved from text input
    var lastCid = null;
    
    /*
     * \brief Search citation in the user's bibliography, then add the
     *        result in the text area.
     * @param cid Identifier for the bibliography entry.
     */
    function getCitation(cid) {
        if (!cid)
            return;
        
        $.ajax({
            url: mw.config.get('wgScript'),
                data: {
                    title: 'Utente:' + 
                           mw.config.get('wgUserName') + 
                           '/Bibliografia',
                    action: 'raw'
                },
                async: false,
                cache: false,
                dataType: 'text',
                success: function(text) {
                    
                    var bibliography = text.match(/<pre>([\s\S]*?)<\/pre>/)[1];
                    var cidRegex = new RegExp(
                        '{{(?:(?!}})[\\s\\S])*?\\|\\s*cid\\s*=\\s*' + 
                        cid + 
                        '[\\s\\S]*?}}', 'g')
                    
                    matches = bibliography.match(cidRegex);
                }
        });
    }
    
    /*
     * \brief Check whether the event should fire the action or not.
     * @param e Triggering event.
     */
    function triggerCondition(e) {
        return e.altKey   == alt     &&
               e.shiftKey == shift   &&
               e.metaKey  == meta    && 
               e.ctrlKey  == ctrl    &&
               e.keyCode === keyCode;
    }
    
    $(function() {
        inputArea.keydown(function(e) {
            // check condition
            if (!triggerCondition(e))
                return;
                
            // suppress browser's default response on shortcut keystroke
            keystrokeDefault = false;
            
            // get cursor position
            var cursor = inputArea.textSelection('getCaretPosition');
            
            var prevText, beginning, cid;
            
            // retrieve cid, if present
            prevText = inputArea.val().substring(0, cursor);
            beginning = prevText.lastIndexOf('{{');
            prevText = prevText.substring(beginning);
            cid = prevText.match(/{{cid:(.*)/);
            
            // select text to be substituted with full citation
            inputArea.textSelection('setSelection', 
                {start: beginning, end: cursor});
            

            // new search or scrolling results?
            if (cid) {
                // new search
                cid = cid[1].trim();
                lastCid = cid;
                index   = 0;
                getCitation(cid);
            } else {
                // scrolling results
                if (!matches)
                    return;
                var r = new RegExp(
                    '^{{[\\s\\S]*?cid\\s*=\\s*' + 
                    lastCid + 
                    '[\\s\\S]*?}}$')
                // ensure the last result is under the cursor
                if (!prevText.match(r))
                    return;
                index = (index + 1) % matches.length;
            }
            
            var citation = matches[index];
        
            // insert citation in the input area
            inputArea.textSelection('encapsulateSelection', 
                {peri: citation, replace: true});
        });
        
        // prevent default browser action, when needed only
        inputArea.keypress(function(e) {
            if (triggerCondition(e))
                return keystrokeDefault;
        });
    });
}(mediaWiki, jQuery));