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

Материал из Decimal Wiki
Перейти к навигации Перейти к поиску
Нет описания правки
Нет описания правки
 
(не показано 6 промежуточных версий этого же участника)
Строка 1: Строка 1:
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */
/**
* Код MediaWiki:Common.js безусловно загружается всем пользователям на всех страницах.
* Во избежание отправки лишних запросов по возможности не используйте здесь mw.loader.using
* с модулями, которые не загружаются по умолчанию
* (см.[[w:Обсуждение MediaWiki:Common.js#Список модулей, загружаемых по умолчанию]]). В таком случае
* лучше создать скрытый гаджет, загружаемый по умолчанию, и добавить ему нужные модули в качестве
* зависимостей.
*/


if (mwCustomEditButtons) {
// Edit Summary buttons
  mwCustomEditButtons[mwCustomEditButtons.length] = {
function SummaryButtons(){
"imageFile": "http://upload.wikimedia.org/wikipedia/en/c/c8/Button_redirect.png",
  var wpSummary = document.getElementById('wpSummary')
  "speedTip": "Redirect",
  if (!wpSummary) return
"tagOpen": "#REDIRECT [[",
  wpSummaryBtn = document.createElement('span') //global var
"tagClose": "]]",
  wpSummaryBtn.id = 'userSummaryButtonsA'
  "sampleText": "Insert text"};
  wpSummary.parentNode.insertBefore(wpSummaryBtn, wpSummary.nextSibling)
  addSumButton('викиф.', 'викификация', 'Произведена викификация')
mwCustomEditButtons[mwCustomEditButtons.length] = {
  addSumButton('оформл.', 'оформление', 'Улучшено оформление')
"imageFile": "http://upload.wikimedia.org/wikipedia/en/c/c9/Button_strike.png",
  addSumButton('орфогр.', 'орфография', 'Поправлена орфография')
"speedTip": "Strike",
  addSumButton('пункт.', 'пунктуация', 'Изменена пунктуация')
  "tagOpen": "<s>",
  addSumButton('стиль', 'стиль', 'Улучшен стиль текста')
"tagClose": "</s>",
  addSumButton('интервики', 'интервики', 'Исправлены межъязыковые ссылки (интервики)')
"sampleText": "Strike-through text"};
  addSumButton('кат.', 'категория', 'Исправлена категоризация')
  addSumButton('шаблон', 'шаблон', 'Добавлен / изменён шаблон')
mwCustomEditButtons[mwCustomEditButtons.length] = {
  addSumButton('к удал.', 'к удалению', 'Страница предложена к удалению')
  "imageFile": "http://upload.wikimedia.org/wikipedia/en/1/13/Button_enter.png",
  addSumButton('доп.', 'дополнение', 'Добавлены новые сведения')
"speedTip": "Line break",
  addSumButton('илл.', 'иллюстрация', 'Размещена иллюстрация')
"tagOpen": "<br />",
  addSumButton('обнов.', 'обновление данных', 'Обновлены устаревшие данные')
"tagClose": "",
  addSumButton('качество', 'качество текста', 'Уточнено качество текста')
"sampleText": ""};
  addSumButton('источн.', 'источник', 'Указан источник текста')
}
mwCustomEditButtons[mwCustomEditButtons.length] = {
  "imageFile": "http://upload.wikimedia.org/wikipedia/en/8/80/Button_upper_letter.png",
"speedTip": "Superscript",
  "tagOpen": "<sup>",
"tagClose": "</sup>",
  "sampleText": "Superscript text"};
mwCustomEditButtons[mwCustomEditButtons.length] = {
"imageFile": "http://upload.wikimedia.org/wikipedia/en/7/70/Button_lower_letter.png",
"speedTip": "Subscript",
  "tagOpen": "<sub>",
"tagClose": "</sub>",
  "sampleText": "Subscript text"};
mwCustomEditButtons[mwCustomEditButtons.length] = {
"imageFile": "http://upload.wikimedia.org/wikipedia/en/5/58/Button_small.png",
"speedTip": "Small",
  "tagOpen": "<small>",
"tagClose": "</small>",
  "sampleText": "Small Text"};
mwCustomEditButtons[mwCustomEditButtons.length] = {
"imageFile": "http://upload.wikimedia.org/wikipedia/en/3/34/Button_hide_comment.png",
"speedTip": "Insert hidden Comment",
  "tagOpen": "<!-- ",
"tagClose": " -->",
  "sampleText": "Comment"};
mwCustomEditButtons[mwCustomEditButtons.length] = {
  "imageFile": "http://upload.wikimedia.org/wikipedia/en/f/fd/Button_blockquote.png",
"speedTip": "Insert block of quoted text",
  "tagOpen": "<blockquote>\n",
"tagClose": "\n</blockquote>",
  "sampleText": "Block quote"};
mwCustomEditButtons[mwCustomEditButtons.length] = {
"imageFile": "http://upload.wikimedia.org/wikipedia/en/6/60/Button_insert_table.png",
"speedTip": "Insert a table",
  "tagOpen": '{| class="wikitable"\n|-\n',
"tagClose": "\n|}",
  "sampleText": "! header 1\n! header 2\n! header 3\n|-\n| row 1, cell 1\n| row 1, cell 2\n| row 1, cell 3\n|-\n| row 2, cell 1\n| row 2, cell 2\n| row 2, cell 3"};


  mwCustomEditButtons[mwCustomEditButtons.length] = {
function addSumButton(name, text, title) {
  "imageFile": "http://upload.wikimedia.org/wikipedia/commons/7/79/Button_reflink.png",
  var btn = document.createElement('a')
  "speedTip": "Insert a reference",
  btn.appendChild(document.createTextNode(name))
  "tagOpen": "<ref>",
  btn.title = title
  "tagClose": "</ref>",
  btn.onclick = function(){insertSummary(text)}
"sampleText": "Insert footnote text here"};
  wpSummaryBtn.appendChild(btn)
}


  }
function insertSummary(text) {
  var wpSummary = document.querySelector("input[name='wpSummary']");
if (wpSummary.value.indexOf(text) != -1) return
if (wpSummary.value.match(/[^,; \/]$/)) wpSummary.value += ','
if (wpSummary.value.match(/[^ ]$/)) wpSummary.value += ' '
wpSummary.value += text
}


/*Добавляем кнопку викификатора*/
/*Добавляем кнопку викификатора*/
Строка 117: Строка 75:
         } );
         } );
}
}
//Collapsiblе:
var NavigationBarShowDefault = 2
var NavigationBarHide = '[скрыть]'
var NavigationBarShow = '[показать]'
function collapsibleTables(){
var Table, HRow,  HCell, btn, a, tblIdx = 0, colTables = []
var allTables = document.getElementsByTagName('table')
for (var i=0; Table = allTables[i]; i++){
  if (!$(Table).hasClass('collapsible')) continue
  if (!(HRow=Table.rows[0])) continue
  if (!(HCell=HRow.getElementsByTagName('th')[0])) continue
  Table.id = 'collapsibleTable' + tblIdx
  btn = document.createElement('span')
  btn.style.cssText = 'float:right; font-weight:normal; font-size:smaller'
  a = document.createElement('a')
  a.id = 'collapseButton' + tblIdx
  a.href = 'javascript:collapseTable(' + tblIdx + ');'
  a.style.color = HCell.style.color
  a.appendChild(document.createTextNode(NavigationBarHide))
  btn.appendChild(a)
  HCell.insertBefore(btn, HCell.childNodes[0])
  colTables[tblIdx++] = Table
}
for (var i=0; i < tblIdx; i++)
  if ((tblIdx > NavigationBarShowDefault && $(colTables[i]).hasClass('autocollapse')) || $(colTables[i]).hasClass('collapsed'))
    collapseTable(i)
}
function collapseTable (idx){
var Table = document.getElementById('collapsibleTable' + idx)
var btn = document.getElementById('collapseButton' + idx)
if (!Table || !btn) return false
var Rows = Table.rows
var isShown = (btn.firstChild.data == NavigationBarHide)
btn.firstChild.data = isShown ?  NavigationBarShow : NavigationBarHide
var disp = isShown ? 'none' : Rows[0].style.display
for (var i=1; i < Rows.length; i++)
    Rows[i].style.display = disp
}
function collapsibleDivs(){
var navIdx = 0, colNavs = [], i, NavFrame
var divs = document.getElementById('content').getElementsByTagName('div')
for (i=0; NavFrame = divs[i]; i++) {
  if (!$(NavFrame).hasClass('NavFrame')) continue
  NavFrame.id = 'NavFrame' + navIdx
  var a = document.createElement('a')
  a.className = 'NavToggle'
  a.id = 'NavToggle' + navIdx
  a.href = 'javascript:collapseDiv(' + navIdx + ');'
  a.appendChild(document.createTextNode(NavigationBarHide))
  for (var j=0; j < NavFrame.childNodes.length; j++)
    if ($(NavFrame.childNodes[j]).hasClass('NavHead'))
      NavFrame.childNodes[j].appendChild(a)
  colNavs[navIdx++] = NavFrame
}
for (i=0; i < navIdx; i++)
  if ((navIdx > NavigationBarShowDefault && !$(colNavs[i]).hasClass('expanded')) || $(colNavs[i]).hasClass('collapsed'))
    collapseDiv(i)
}
function collapseDiv(idx) {
var div = document.getElementById('NavFrame' + idx)
var btn = document.getElementById('NavToggle' + idx)
if (!div || !btn) return false
var isShown = (btn.firstChild.data == NavigationBarHide)
btn.firstChild.data = isShown ? NavigationBarShow : NavigationBarHide
var disp = isShown ? 'none' : 'block'
for (var child = div.firstChild;  child != null;  child = child.nextSibling)
  if ($(child).hasClass('NavPic') || $(child).hasClass('NavContent'))
      child.style.display = disp
}
function newSectionLink(){
var plus = document.getElementById('ca-addsection')
if (!plus) return
var custom = document.getElementById('add-custom-section')
if (!custom) return
plus.firstChild.setAttribute('href', custom.getElementsByTagName('a')[0].href)
}
function editZeroSection(){
var body = document.getElementById('bodyContent')
if (!body) return
var h2s = body.getElementsByTagName('H2')
var h2 = h2s[0]
if (!h2) return
if (h2.parentNode.id == 'toctitle') h2 = h2s[1]
if (!h2) return
var span = h2.firstChild
if (!span || span.className != 'editsection') return
var zero = span.cloneNode(true)
body.insertBefore(zero, body.firstChild)
var a = zero.getElementsByTagName('a')[0]
if (a.href.indexOf('&section=T') == -1 )  a.title = a.title.replace(/:.*$/,': 0')
else a.title = 'Править секцию: 0'
a.href = mw.config.get('wgScript') + '?title=' + encodeURIComponent(mw.config.get('wgPageName')) + '&action=edit&section=0';
}
importScript('MediaWiki:Input.js');

Текущая версия от 16:38, 27 июня 2024

/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */

// Edit Summary buttons 
function SummaryButtons(){
 var wpSummary = document.getElementById('wpSummary')
 if (!wpSummary) return
 wpSummaryBtn = document.createElement('span') //global var
 wpSummaryBtn.id = 'userSummaryButtonsA'
 wpSummary.parentNode.insertBefore(wpSummaryBtn, wpSummary.nextSibling)
 addSumButton('викиф.', 'викификация', 'Произведена викификация')
 addSumButton('оформл.', 'оформление', 'Улучшено оформление')
 addSumButton('орфогр.', 'орфография', 'Поправлена орфография')
 addSumButton('пункт.', 'пунктуация', 'Изменена пунктуация')
 addSumButton('стиль', 'стиль', 'Улучшен стиль текста')
 addSumButton('интервики', 'интервики', 'Исправлены межъязыковые ссылки (интервики)')
 addSumButton('кат.', 'категория', 'Исправлена категоризация')
 addSumButton('шаблон', 'шаблон', 'Добавлен / изменён шаблон')
 addSumButton('к удал.', 'к удалению', 'Страница предложена к удалению')
 addSumButton('доп.', 'дополнение', 'Добавлены новые сведения')
 addSumButton('илл.', 'иллюстрация', 'Размещена иллюстрация')
 addSumButton('обнов.', 'обновление данных', 'Обновлены устаревшие данные')
 addSumButton('качество', 'качество текста', 'Уточнено качество текста')
 addSumButton('источн.', 'источник', 'Указан источник текста')
}

function addSumButton(name, text, title) {
 var btn = document.createElement('a')
 btn.appendChild(document.createTextNode(name))
 btn.title = title
 btn.onclick = function(){insertSummary(text)}
 wpSummaryBtn.appendChild(btn)
}

function insertSummary(text) {
 var wpSummary = document.querySelector("input[name='wpSummary']");
 if (wpSummary.value.indexOf(text) != -1) return 
 if (wpSummary.value.match(/[^,; \/]$/)) wpSummary.value += ','
 if (wpSummary.value.match(/[^ ]$/)) wpSummary.value += ' '
 wpSummary.value += text
}

/*Добавляем кнопку викификатора*/
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 ) {
        mw.loader.load( '//ru.wikipedia.org/w/index.php?title=MediaWiki:Gadget-wikificator.js&action=raw&ctype=text/javascript' );
}

var customizeToolbar = function() {

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
        'section': 'advanced',
        'group': 'format',
        'tools': {
                'wikify': {
                        label: 'Викификатор',
                        type: 'button',
                        icon: '//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png',
                             action: {
                                  type: 'callback',
                                       execute: function(context){
                                              Wikify();
                                       } 
                             }
                }
        }
} );
};
 
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 ) {
        mw.loader.using( 'user.options', function () {
                if ( mw.user.options.get('usebetatoolbar') ) {
                        mw.loader.using( 'ext.wikiEditor.toolbar', function () {
                                $(document).ready( customizeToolbar );
                        } );
                }
        } );
}

//Collapsiblе: 

var NavigationBarShowDefault = 2
var NavigationBarHide = '[скрыть]'
var NavigationBarShow = '[показать]'

function collapsibleTables(){
 var Table, HRow,  HCell, btn, a, tblIdx = 0, colTables = []
 var allTables = document.getElementsByTagName('table')
 for (var i=0; Table = allTables[i]; i++){
   if (!$(Table).hasClass('collapsible')) continue
   if (!(HRow=Table.rows[0])) continue
   if (!(HCell=HRow.getElementsByTagName('th')[0])) continue
   Table.id = 'collapsibleTable' + tblIdx
   btn = document.createElement('span')
   btn.style.cssText = 'float:right; font-weight:normal; font-size:smaller'
   a = document.createElement('a')
   a.id = 'collapseButton' + tblIdx
   a.href = 'javascript:collapseTable(' + tblIdx + ');' 
   a.style.color = HCell.style.color
   a.appendChild(document.createTextNode(NavigationBarHide))
   btn.appendChild(a)
   HCell.insertBefore(btn, HCell.childNodes[0])
   colTables[tblIdx++] = Table
 }
 for (var i=0; i < tblIdx; i++)
   if ((tblIdx > NavigationBarShowDefault && $(colTables[i]).hasClass('autocollapse')) || $(colTables[i]).hasClass('collapsed'))
     collapseTable(i)
}

function collapseTable (idx){
 var Table = document.getElementById('collapsibleTable' + idx)
 var btn = document.getElementById('collapseButton' + idx)
 if (!Table || !btn) return false
 var Rows = Table.rows
 var isShown = (btn.firstChild.data == NavigationBarHide)
 btn.firstChild.data = isShown ?  NavigationBarShow : NavigationBarHide
 var disp = isShown ? 'none' : Rows[0].style.display
 for (var i=1; i < Rows.length; i++) 
    Rows[i].style.display = disp
}

function collapsibleDivs(){
 var navIdx = 0, colNavs = [], i, NavFrame
 var divs = document.getElementById('content').getElementsByTagName('div')
 for (i=0; NavFrame = divs[i]; i++) {
   if (!$(NavFrame).hasClass('NavFrame')) continue
   NavFrame.id = 'NavFrame' + navIdx
   var a = document.createElement('a')
   a.className = 'NavToggle'
   a.id = 'NavToggle' + navIdx
   a.href = 'javascript:collapseDiv(' + navIdx + ');'
   a.appendChild(document.createTextNode(NavigationBarHide))
   for (var j=0; j < NavFrame.childNodes.length; j++)
     if ($(NavFrame.childNodes[j]).hasClass('NavHead'))
       NavFrame.childNodes[j].appendChild(a)
   colNavs[navIdx++] = NavFrame
 }
 for (i=0; i < navIdx; i++)
  if ((navIdx > NavigationBarShowDefault && !$(colNavs[i]).hasClass('expanded')) || $(colNavs[i]).hasClass('collapsed'))
     collapseDiv(i)
}

function collapseDiv(idx) {
 var div = document.getElementById('NavFrame' + idx)
 var btn = document.getElementById('NavToggle' + idx)
 if (!div || !btn) return false
 var isShown = (btn.firstChild.data == NavigationBarHide)
 btn.firstChild.data = isShown ? NavigationBarShow : NavigationBarHide 
 var disp = isShown ? 'none' : 'block'
 for (var child = div.firstChild;  child != null;  child = child.nextSibling)
   if ($(child).hasClass('NavPic') || $(child).hasClass('NavContent')) 
      child.style.display = disp
}


function newSectionLink(){
 var plus = document.getElementById('ca-addsection')
 if (!plus) return
 var custom = document.getElementById('add-custom-section')
 if (!custom) return
 plus.firstChild.setAttribute('href', custom.getElementsByTagName('a')[0].href)
}
 
 
function editZeroSection(){
 var body = document.getElementById('bodyContent')
 if (!body) return
 var h2s = body.getElementsByTagName('H2')
 var h2 = h2s[0]
 if (!h2) return
 if (h2.parentNode.id == 'toctitle') h2 = h2s[1]
 if (!h2) return
 var span = h2.firstChild
 if (!span || span.className != 'editsection') return
 var zero = span.cloneNode(true)
 body.insertBefore(zero, body.firstChild)
 var a = zero.getElementsByTagName('a')[0]
 if (a.href.indexOf('&section=T') == -1 )  a.title = a.title.replace(/:.*$/,': 0')
 else a.title = 'Править секцию: 0'
 a.href = mw.config.get('wgScript') + '?title=' + encodeURIComponent(mw.config.get('wgPageName')) + '&action=edit&section=0';
}

importScript('MediaWiki:Input.js');