MediaWiki:Gadget-preview.js: различия между версиями
Перейти к навигации
Перейти к поиску
>Edward Chernenko м убрал лабуду |
мНет описания правки |
||
| (не показана 1 промежуточная версия этого же участника) | |||
| Строка 1: | Строка 1: | ||
/** | |||
* Gadget-preview -- гаджет Ajax-предпросмотра. | |||
* Взят из Википедии (https://ru.wikipedia.org/wiki/MediaWiki:Gadget-preview.js). | |||
*/ | |||
ajaxPreviewMsg = { | |||
emptydiff: 'Изменений нет.', | |||
difftip: 'Нажмите кнопку с зажатым Shift для сравнения с редактируемой старой версией', | |||
diff2old: 'Это сравнение со старой версией', | |||
viewtip: 'Нажмите кнопку с зажатым Shift для обновления также категорий и шаблонов' | |||
}; | |||
if (/^(edit|submit)$/.test(mw.config.get('wgAction')) && | |||
(!/^(Special|Module)$/.test(mw.config.get('wgCanonicalNamespace')) || | |||
/\/doc$/.test(mw.config.get('wgPageName')) | |||
) | |||
) { | |||
$(function () { | |||
ajaxPreviewPos = window.ajaxPreviewPos || 'right'; | |||
if (ajaxPreviewPos !== 'bottom') { | |||
var previewToolbar = $('<div>') | |||
.css('float', ajaxPreviewPos); | |||
if (mw.user.options.get('usebetatoolbar') || $.wikiEditor) { | |||
$('#wikiPreview').after( | |||
$('<div>') | |||
.css('width', '100%') | |||
.css('clear', 'both'), | |||
previewToolbar | |||
); | |||
} else { | |||
var el = $('#toolbar'); | |||
if (el.length) { | |||
el.prepend(previewToolbar); | |||
} else { | |||
$('#editform').before(previewToolbar); | |||
} | |||
} | |||
} | |||
addBtn(window.ajaxPreviewButton, 'wpPreview', window.ajaxPreviewKey || 'p'); | |||
addBtn(window.ajaxDiffButton, 'wpDiff', window.ajaxDiffKey || 'v'); | |||
var wkPreview = $('#wikiPreview'), | |||
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()); | |||
} | |||
}); | |||
} | } | ||
Текущая версия от 11:09, 21 марта 2019
/**
* Gadget-preview -- гаджет Ajax-предпросмотра.
* Взят из Википедии (https://ru.wikipedia.org/wiki/MediaWiki:Gadget-preview.js).
*/
ajaxPreviewMsg = {
emptydiff: 'Изменений нет.',
difftip: 'Нажмите кнопку с зажатым Shift для сравнения с редактируемой старой версией',
diff2old: 'Это сравнение со старой версией',
viewtip: 'Нажмите кнопку с зажатым Shift для обновления также категорий и шаблонов'
};
if (/^(edit|submit)$/.test(mw.config.get('wgAction')) &&
(!/^(Special|Module)$/.test(mw.config.get('wgCanonicalNamespace')) ||
/\/doc$/.test(mw.config.get('wgPageName'))
)
) {
$(function () {
ajaxPreviewPos = window.ajaxPreviewPos || 'right';
if (ajaxPreviewPos !== 'bottom') {
var previewToolbar = $('<div>')
.css('float', ajaxPreviewPos);
if (mw.user.options.get('usebetatoolbar') || $.wikiEditor) {
$('#wikiPreview').after(
$('<div>')
.css('width', '100%')
.css('clear', 'both'),
previewToolbar
);
} else {
var el = $('#toolbar');
if (el.length) {
el.prepend(previewToolbar);
} else {
$('#editform').before(previewToolbar);
}
}
}
addBtn(window.ajaxPreviewButton, 'wpPreview', window.ajaxPreviewKey || 'p');
addBtn(window.ajaxDiffButton, 'wpDiff', window.ajaxDiffKey || 'v');
var wkPreview = $('#wikiPreview'),
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());
}
});
}