MediaWiki:Gadget-preview.js: различия между версиями

>Edward Chernenko
м убрал лабуду
мНет описания правки
 
(не показана 1 промежуточная версия этого же участника)
Строка 1: Строка 1:
function ajaxPreviewInit(){
/**
if ((wgNamespaceNumber % 2 == 0) && /\.(js|css)$/.test(wgTitle)) return
* Gadget-preview -- гаджет Ajax-предпросмотра.
if (typeof ajaxPreviewKey != 'string') ajaxPreviewKey = 'p'
* Взят из Википедии (https://ru.wikipedia.org/wiki/MediaWiki:Gadget-preview.js).
if (typeof ajaxDiffKey != 'string') ajaxDiffKey  = 'v'
*/
ajaxPreviewPos = window.ajaxPreviewPos || 'right'
 
if (ajaxPreviewPos != 'bottom'){
ajaxPreviewMsg = {
  var tOld = document.getElementById('toolbar') || document.getElementById('wpTextbox1')
    emptydiff: 'Изменений нет.',
  tOld.style.clear = 'none'
    difftip: 'Нажмите кнопку с зажатым Shift для сравнения с редактируемой старой версией',
  var d = document.createElement('div'); d.style.cssText = 'width:100%; clear:both'
    diff2old: 'Это сравнение со старой версией',
  tOld.parentNode.insertBefore(d, tOld)
    viewtip: 'Нажмите кнопку с зажатым Shift для обновления также категорий и шаблонов'
  var tNew = document.createElement('div'); tNew.style.cssText = 'float:'+ ajaxPreviewPos
};
  tOld.parentNode.insertBefore(tNew, tOld)
 
}
 
addBtn(window.ajaxPreviewButton, 'wpPreview', ajaxPreviewKey)
if (/^(edit|submit)$/.test(mw.config.get('wgAction')) &&
addBtn(window.ajaxDiffButton, 'wpDiff', ajaxDiffKey)
    (!/^(Special|Module)$/.test(mw.config.get('wgCanonicalNamespace')) ||
function addBtn(name, id, akey){
        /\/doc$/.test(mw.config.get('wgPageName'))
  var btnOld = document.getElementById(id)
    )
  if (!btnOld) return
) {
  //var
    $(function () {
  btn = document.createElement('input'); btn.type = 'button'
        ajaxPreviewPos = window.ajaxPreviewPos || 'right';
  btn.onclick = ajaxPreviewClick; btn.id = id + 'Live'
 
  if (!name){ //extract last word from standard buttons
        if (ajaxPreviewPos !== 'bottom') {
    name = btnOld.value.split(' '); name = name[name.length-1]
            var previewToolbar = $('<div>')
    name = name.substring(0,1).toUpperCase() + name.substring(1)  
                .css('float', ajaxPreviewPos);
  }
            if (mw.user.options.get('usebetatoolbar') || $.wikiEditor) {
  btn.value = name; btn.title = btnOld.value + ' (Ajax)'
                $('#wikiPreview').after(
  if (ajaxPreviewPos == 'bottom'){
                    $('<div>')
    btnOld.parentNode.insertBefore(btn, btnOld)
                        .css('width', '100%')
    btn.value = btnOld.value
                        .css('clear', 'both'),
    btnOld.value = '>'
                    previewToolbar
  }else{
                );
    btn.style.cssText = 'height:22px; padding:0 1px'
            } else {
    tNew.appendChild(btn)
                var el = $('#toolbar');
  }
                if (el.length) {
  if (akey){ //reassign acces key
                    el.prepend(previewToolbar);
    if (btnOld.accessKey == akey){  
                } else {
      btnOld.accessKey = ''
                    $('#editform').before(previewToolbar);
  //btnOld.setAttribute('accesskey', '')
                }
      btnOld.title = btnOld.title.replace(tooltipAccessKeyRegexp, '')
            }
    }
        }
    //btn.setAttribute('accesskey', akey)
        addBtn(window.ajaxPreviewButton, 'wpPreview', window.ajaxPreviewKey || 'p');
btn.accessKey = akey
        addBtn(window.ajaxDiffButton, 'wpDiff', window.ajaxDiffKey || 'v');
    btn.title += ' ['+tooltipAccessKeyPrefix+akey+']'
 
  }
        var wkPreview = $('#wikiPreview'),
  btn.value2 = btn.value
            frm = document.editform;
}
        if (!wkPreview.length || !frm) return;
        $('#wpPreviewLive, #wpDiffLive').click(run);
 
        var cssWait, cssPreview, cssOutdated;
        var isDiff, isFullPreview, btn, oldHeight, htm, scriptTip;
        var mm = window.ajaxPreviewMsg || {};
 
        function run(e) {
            btn = $(this);
            btn.attr('orig', btn.val());
            btn.val('...');
 
            $('#wikiDiff, #newarticletext').hide();
            oldHeight = wkPreview.height();
            scriptTip = '';
 
            if (!cssWait) {
                cssWait = mw.util.addCSS('#wikiPreview { opacity: 0.3; color: gray; }' +
                    'body { cursor: wait; }');
            } else {
                cssWait.disabled = false;
            }
 
            var url = mw.config.get('wgScriptPath') + '/api.php?format=json', data, ext;
            var txt = $('#wpTextbox1').textSelection('getContents');
 
            isDiff = btn.attr('id') == 'wpDiffLive';
 
            if (isDiff) {
                mw.loader.load('mediawiki.diff.styles');
 
                url += '&action=query&prop=revisions';
                data = {
                    titles: mw.config.get('wgPageName').replace(/_/g, ' '),
                    rvdifftotext: txt
                };
 
                if (frm.wpSection.value) {
                    url += '&rvsection=' + frm.wpSection.value;
                }
 
                // Can compare to currently edited older version, not to the latest
                if (frm.oldid.value && frm.oldid.value != '0') {
                    if (e.shiftKey) {
                        url += '&rvstartid=' + frm.oldid.value + '&rvendid=' + frm.oldid.value;
                        scriptTip = mm.diff2old;
                    } else {
                        scriptTip = mm.difftip;
                    }
                }
            } else {  // Preview
                if (frm.wpSection.value) {
                    txt += '<br><references />';
                }
 
                url += '&action=parse&pst=&disablepp=&prop=text|modules';
                data = {
                    title: mw.config.get('wgPageName'),
                    text: txt,
                    summary: frm.wpSummary.value
                };
 
                if (window.ajaxPreviewFull || e.shiftKey) {
                    isFullPreview = true;
                    url += '|categorieshtml|languageshtml|templates';
                } else {
                    isFullPreview = false;
                    if (mw.config.get('wgNamespaceNumber') === 0) {
                        scriptTip = mm.viewtip;
                    }
                }
            }
 
            // Switch to multipart to decrease sent data volume on non-Latin languages
            var boundary = '--------123xyz' + Math.random(),
                dat2 = '';
            for (var nm in data) {
                dat2 += '--' + boundary + '\nContent-Disposition: form-data; name="' + nm + '"\n\n' + data[nm] +
                    '\n';
            }
 
            // Send
            $.ajax({
                url: url,
                type: 'post',
                data: dat2 + '--' + boundary,
                contentType: 'multipart/form-data; charset=UTF-8; boundary=' + boundary,
                success: receive
            });
        }
 
        function receive(resp) {
            cssWait.disabled = true;
            btn.val(btn.attr('orig'));
            if (window.currentFocused) {
                currentFocused.focus();
            }
 
            htm = '';
 
            try {
                if (isDiff) {
                    htm = resp &&
                        resp.query &&
                        resp.query.pages &&
                        resp.query.pages[mw.config.get('wgArticleId')] &&
                        resp.query.pages[mw.config.get('wgArticleId')] &&
                        resp.query.pages[mw.config.get('wgArticleId')].revisions &&
                        resp.query.pages[mw.config.get('wgArticleId')].revisions[0] &&
                        resp.query.pages[mw.config.get('wgArticleId')].revisions[0].diff &&
                        resp.query.pages[mw.config.get('wgArticleId')].revisions[0].diff['*'];
                    if (htm) {
                        htm = '<table class="diff">' +
                            '<col class="diff-marker"><col class="diff-content">' +
                            '<col class="diff-marker"><col class="diff-content">' +
                            htm +
                            '</table>';
                    } else {
                        if (htm === '') {
                            htm = mm.emptydiff;
                        } else {
                            if (resp && resp.query && resp.query.pages && resp.query.pages[-1] &&
                                resp.query.pages[-1].missing === ''
                            ) {
                                htm = 'Страница ещё не создана — не с чем показывать разницу.';
                            } else {
                                htm = 'Ошибка при получении разницы версий.';
                            }
                        }
                    }
                } else {
                    resp = resp.parse;
                    htm = resp.text['*'];
                    if (frm.wpSection.value == 'new') { // Add summary as H2
                        htm = '<h2>' + resp.parsedsummary['*'] + '</h2>' + htm;
                    } else {
                        var $sum = $(frm).find('div.mw-summary-preview');  // Create summary preview if needed
                        if (!$sum.length) {
                            $sum = $('<div>')
                                .addClass('mw-summary-preview')
                                .insertAfter('#wpSummary');
                        }
                        $sum.html('<span class="comment">' + resp.parsedsummary['*'] + '</span>');
                    }
                    if (resp.modules) {
                        mw.loader.load(
                            resp.modules.concat(resp.modulescripts, resp.modulestyles)
                        );
                    }
                }
            } catch (err) {
                htm = 'error: ' + err;
            }
 
            htm =
                (scriptTip ?
                    '<small style="float:right; margin-top:0.2em; border:1px solid #a2a9b1; padding:1px 5px;">' +
                    '<span style="margin-right:0.4em; color:#cc0000; font-weight:bold;">!</span>' + scriptTip +
                    '</small>' :
                    '') +
                '<h3 id="ajax-preview-h3">' + btn.val() + ' (ajax)</h3>' +
                '<hr>' +  // font-style:italic; text-align:right;
                htm;
            wkPreview.html(htm).show();
 
            // New content is available, fire the hook
            mw.hook('wikipage.content').fire(wkPreview);
 
            if (window.ajaxPreviewScrollTop) {
                wkPreview[0].scrollIntoView();
            } else {
                $(window).scrollTop($(window).scrollTop() + wkPreview.height() - oldHeight);
            }
 
            if (!isDiff) {
                finalizePreview(resp);
            }
        }
 
        function finalizePreview(resp) {
            // Demonstrate that hiddencats will not be updated
            if (!cssPreview) {
                cssPreview = mw.util.addCSS(
                    'span.editsection { display:none; }' +
                    '.hiddencats { opacity: 0.5; }'
                );
            }
 
            if ($('.tex').length && mw.user.options.get('math') === '6') { // 6 — mathjax mode
                mw.loader.using('ext.math.mathjax.enabler', function () {
                    $('#wikiPreview').renderTex();
                });
            }
            if (window.ajaxPreviewExec) {
                ajaxPreviewExec(wkPreview[0]);
            }
 
 
            // !!! [[mediazilla:36476]]
            if ($('body').hasClass('ltr')) {
                $('#wikiPreview').addClass('mw-content-ltr');
            }
 
            if (!isFullPreview) {
                if (!cssOutdated) {
                    cssOutdated = mw.util.addCSS('.templatesUsed, #p-lang, #catlinks { opacity:0.5; }');
                } else {
                    cssOutdated.disabled = false;
                }
                // $('#p-lang, #catlinks').attr('title', 'Not updated by latest preview')
                return;
            }
 
            // Otherwise update other areas
            if (cssOutdated) {
                cssOutdated.disabled = true;
            }
 
            $('#catlinks').replaceWith(resp.categorieshtml['*']);
 
            if (resp.languageshtml) {
                htm = resp.languageshtml['*'];
                var plang = $('#p-lang');
                if (!plang.length) {
                    plang = $('#p-tb')
                        .clone(true)
                        .attr('id', 'p-lang')
                        .insertAfter('#p-tb')
                        .find('h5')
                        .text(htm.replace(/[:<].+$/, ''))
                        .end();
                }
                plang.find('ul').html(
                    '<li>' + htm.replace(/^[^<]*/, '').replace(/<\/a>[^<]+/g, '</a></li><li>') + '</li>'
                );
            }
 
            htm = '';
            var tt = resp.templates;
            for (var i = 0; i < tt.length; i++) {
                htm += '<li><a href="/' + encodeURIComponent(tt[i]['*']) + '"' +
                    (typeof tt[i].exists == 'string' ? '' : ' class="new"') +
                    '>' + tt[i]['*'] + '</a></li>';
            }
            $('#editform')
                .find('div.templatesUsed')
                .find('ul')
                .html(htm);
        }
 
        function addBtn(name, id, akey) {
            var btnOld = $('#' + id);
            if (!btnOld.length) {
                return;
            }
            var btn = $('<input type="button" id="' + id + 'Live" title="' + btnOld.val() + ' (ajax)">');
            if (ajaxPreviewPos == 'bottom') {
                btn.val('>').insertAfter('#' + id + 'Widget');
            } else {
                if (!name) {  // Extract last word from standard buttons
                    name = btnOld.val();
                    var i = name.lastIndexOf(' ') + 1;
                    name = name.substring(i, i + 1).toUpperCase() + name.substring(i + 1);
                }
                btn.val(name)
                    .css('height', '22px')
                    .css('padding', '0 1px')
                    .appendTo(previewToolbar);
            }
            mw.loader.using('jquery.accessKeyLabel', function () {
                if (akey) { // Reassign access key
                    if (btnOld.attr('accesskey') == akey) {
                        btnOld
                            .removeAttr('accesskey')
                            .updateTooltipAccessKeys('');
                    }
                    btn
                        .attr('accesskey', akey)
                        .updateTooltipAccessKeys(akey);
                }
            });
            btn.width(btn.outerWidth());
        }
    });
}
}
function ajaxPreviewClick(){ajaxPreviewRun(this)}
function ajaxPreviewRun(btn){
var wkPreview = document.getElementById('wikiPreview'), form = document.editform
var aj = sajax_init_object()
if (!wkPreview || !form || !aj) return
var oldHeight = wkPreview.offsetHeight
var el, htm, isDiff = (btn.id=='wpDiffLive')
wkPreview.style.opacity = '0.3'; wkPreview.style.color = 'gray'; document.body.style.cursor = 'wait'
if (el=document.getElementById('wikiDiff')) el.style.display = 'none'
if (el=document.getElementById('newarticletext')) el.style.display = 'none'
btn.style.width = Math.max(btn.scrollWidth, btn.offsetWidth) + 'px';  btn.value = '...'
//prepare
var txt = form.wpTextbox1.value, action = form.action
var boundary = '--------123xyz', data = ''
if (isDiff){
  addData('wpDiff', ''); addData('wpStarttime'); addData('wpEdittime')
  if (!window.ajaxPreview_CSS) ajaxPreview_CSS = importStylesheetURI('/skins-1.5/common/diff.css')
}else{
  action += '&live'
  if (form.wpSection && form.wpSection.value) txt += '\n<br /><references />'
}
addData('wpTextbox1', txt); addData('wpSection'); addData('wpSummary')
//send
aj.open('POST', action, true)
aj.setRequestHeader('Content-Type', 'multipart/form-data; boundary='+boundary)
aj.send(data + '--' + boundary)
aj.onreadystatechange = function(){
  if (aj.readyState != 4) return
  zzh = aj.responseText // !!!
  wkPreview.style.display = 'block'
  if (isDiff){
    var htm = aj.responseText
    var p1 = htm.indexOf("<table class='diff'>" )
    var p2 = htm.indexOf('</table>', p1)
    htm = (p1!=-1 && p2!=-1) ? htm.substring(p1, p2+8) : 'Error'
  }else{
    htm = aj.responseText.replace(/&gt;/g,'>').replace(/&lt;/g,'<').replace(/&quot;/g,'"').replace(/&amp;/g,'&').replace(/&apos;/g,"'")
  }
  wkPreview.innerHTML = htm
  btn.value = btn.value2
  if (el = wkPreview.getElementsByTagName('h2')[0]){
    if (el.style.textAlign != 'right') el.innerHML +=  ' (Ajax)'
    el.style.textAlign = 'right'
  }
  if (window.ajaxPreviewScrollTop && wkPreview.scrollIntoView) wkPreview.scrollIntoView()
  else document.documentElement.scrollTop +=  wkPreview.offsetHeight - oldHeight
  wkPreview.style.opacity = ''; wkPreview.style.color = ''; document.body.style.cursor = ''
}
function addData(name, value){
  if (!value) value = form[name] ? form[name].value : ''
  data += '--' + boundary + '\nContent-Disposition: form-data; name="'+name+'"\n\n' + value + '\n'
}
}
if (wgAction=='edit' || wgAction=='submit') addOnloadHook(ajaxPreviewInit);