MediaWiki:Common.js: различия между версиями
Внешний вид
Spark108 (обсуждение | вклад) Отмена версии 1698, сделанной Spark108 (обсуждение) Метка: отмена |
Spark108 (обсуждение | вклад) Нет описания правки |
||
Строка 1: | Строка 1: | ||
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */ | /* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */ | ||
mw.loader.load('/index.php?title=MediaWiki:ServerOnline.js&action=raw&ctype=text/javascript'); | mw.loader.load('/index.php?title=MediaWiki:ServerOnline.js&action=raw&ctype=text/javascript'); | ||
( function() { | |||
'use strict'; | |||
/* Переменные для текста в интерфейсе, используюемые в сценарии и выделенные для удобства перевода */ | |||
var i18n = { | |||
// Скрываемые элементы, подгрузка страниц | |||
hideText: 'скрыть', | |||
showText: 'показать', | |||
// Подгрузка страниц | |||
loadErrorTitle: 'Возникла ошибка при загрузке содержимого', | |||
// Загрузка файлов | |||
defaultLicense: 'Лицензия', | |||
more_results: 'И ещё $1 нерешённых проблем.', | |||
no_results: 'Активных отчётов не обнаружено.', | |||
projects: { | |||
bds: 'Bedrock Dedicated Server', | |||
mc: 'Java Edition', | |||
mcd: 'Minecraft Dungeons', | |||
mcl: 'Лаунчер', | |||
mclg: 'Minecraft Legends', | |||
mcpe: 'Bedrock Edition', | |||
realms: 'Realms', | |||
web: 'Веб-сервисы Mojang' | |||
} | |||
}; | |||
/* | |||
* Чтобы не захламлять глобальную область имён переменными, они должны быть | |||
* добавлены в качестве свойства данной глобальной переменной. | |||
* | |||
* Например, вместо | |||
* myVar = 'blah'; | |||
* используйте | |||
* mcw.myVar = 'blah'; | |||
*/ | |||
var mcw = window.mcw = {}; | |||
/* Скрывает вкладки "Править вики-текст", "Просмотреть вики-текст", "Править" если им не хватает места в навигации */ | |||
$("li[id*='ca-watch']").addClass('collapsible'); | |||
$("li[id*='ca-unwatch']").addClass('collapsible'); | |||
$("li[id*='ca-edit']").addClass('collapsible'); | |||
$("li[id*='ca-view']").addClass('collapsible'); | |||
$("li[id*='ca-ve-edit']").addClass('collapsible'); | |||
$("li[id*='ca-viewsource']").addClass('collapsible'); | |||
/* Keep track of delegated events on dynamic content */ | |||
mcw.events = {}; | |||
/* Активируется при добавлении содержимого страниц вики (#mw-content-text, динамически загружаемое содержимое и т. д.) */ | |||
mw.hook( 'wikipage.content' ).add( function( $wikipageContent ) { | |||
/** | |||
* Collapsible elements | |||
* | |||
* Add the "collapsible" class to an element and the child element with class "collapsible-content" | |||
* (or everything but the header row if a table) will be hidden when the element is collapsed. | |||
* | |||
* * Add the class "collapsed" to the element to make it start out collapsed. | |||
* * Add either "collapsetoggle-left" or "collapsetoggle-inline" to the element to choose the collapse | |||
* toggle alignment (defaults to right). | |||
* * Add an ID in the format of "collapsible-<x>" to the element to make any element with the class | |||
* "collapsetoggle-custom" and a matching class in the format of "collapsible-<x>-toggle" control | |||
* the collapsing instead of the standard button. | |||
* If the custom toggle contains an element with the "jslink" class, only that will be clickable. | |||
*/ | |||
( function() { | |||
var $collapsibles = $wikipageContent.find( '.collapsible' ); | |||
if ( !$collapsibles.length ) { | |||
return; | |||
} | |||
var $toggleTemplate = $( '<span>' ).addClass( 'collapsetoggle' ).append( | |||
'[', $( '<span>' ).addClass( 'jslink' ), ']' | |||
); | |||
$collapsibles.each( function() { | |||
var $collapsible = $( this ); | |||
if ( $collapsible.data( 'made-collapsible' ) ) { | |||
return true; | |||
} | |||
var $children = $collapsible.children(); | |||
var showText = $collapsible.data( 'expandtext' ) || i18n.showText; | |||
var hideText = $collapsible.data( 'collapsetext' ) || i18n.hideText; | |||
// If there is no content area, add it | |||
if ( !$collapsible.is( 'table' ) && !$children.filter( '.collapsible-content' ).length ) { | |||
if ( $collapsible.is( 'tr.collapsible-rows' ) ) { | |||
var $collapsibleRows = $collapsible.nextUntil( '.collapsible-rows' ); | |||
if ( $collapsibleRows.hasClass( 'collapsible-row' ) ) { | |||
$collapsibleRows = $collapsibleRows.filter( 'collapsible-row' ); | |||
} else { | |||
$collapsibleRows.addClass( 'collapsible-row' ); | |||
} | |||
if ( $collapsible.hasClass( 'collapsed' ) && !$collapsibleRows.hasClass( 'collapsed' ) ) { | |||
$collapsibleRows.addClass( 'collapsed' ); | |||
} | |||
$collapsible = $collapsible.add( $collapsibleRows ); | |||
} else if ( $collapsible.is( 'tr' ) ) { | |||
$children.addClass( 'collapsible-content' ); | |||
} else { | |||
$collapsible.wrapInner( '<div class="collapsible-content">' ); | |||
} | |||
} | |||
var $toggle; | |||
var id = $collapsible.attr( 'id' ); | |||
if ( id && id.match( /^collapsible-./ ) ) { | |||
$toggle = $( $wikipageContent[0].getElementsByClassName( id + '-toggle' ) ) | |||
.filter( '.collapsetoggle-custom' ).css( 'visibility', 'visible' ); | |||
} | |||
// Create and insert the toggle button if there is no custom one | |||
if ( !$toggle || !$toggle.length ) { | |||
var $toggleContainer; | |||
if ( $collapsible.is( 'table' ) ) { | |||
var $rows = $children.filter( 'thead' ).children(); | |||
if ( !$rows.length ) { | |||
$rows = $children.filter( 'tbody' ).first().children(); | |||
if ( !$rows.length ) { | |||
$rows = $children.filter( 'tr' ); | |||
} | |||
} | |||
$toggleContainer = $rows.first().children().last(); | |||
} else { | |||
$toggleContainer = $children.first(); | |||
if ( $toggleContainer.hasClass( 'collapsible-content' ) ) { | |||
$toggleContainer = $collapsible; | |||
} | |||
} | |||
$toggle = $toggleTemplate.clone(); | |||
if ( $collapsible.hasClass( 'collapsetoggle-inline' ) || $collapsible.hasClass( 'collapse-button-none' ) ) { | |||
$toggleContainer.append( $toggle ); | |||
} else { | |||
$toggleContainer.prepend( $toggle ); | |||
} | |||
} | |||
var $toggleLink = $toggle.find( '.jslink' ); | |||
if ( !$toggleLink.length ) { | |||
$toggleLink = $toggle; | |||
} | |||
$toggleLink.attr( 'tabindex', 0 ).text( hideText ); | |||
// Find max toggle size, and set its min-width to it | |||
var hideWidth = $toggle.width(); | |||
$toggleLink.text( showText ); | |||
var showWidth = $toggle.width(); | |||
if ( hideWidth !== showWidth ) { | |||
$toggle.css( 'min-width', hideWidth > showWidth ? hideWidth : showWidth ); | |||
} | |||
// Set the text back to hide if it's not collapsed to begin with | |||
if ( !$collapsible.first().hasClass( 'collapsed' ) ) { | |||
$toggleLink.text( hideText ); | |||
} | |||
$toggleLink.on( 'click keydown', function( e ) { | |||
// Only trigger on enter press | |||
if ( e.keyCode && e.keyCode !== 13 ) { | |||
return; | |||
} | |||
// Don't toggle when clicking buttons or links inside the toggle | |||
var $target = $( e.target ); | |||
if ( $target.is( 'button' ) || $target.is( 'a' ) ) { | |||
return; | |||
} | |||
$collapsible.toggleClass( 'collapsed' ); | |||
if ( $collapsible.first().hasClass( 'collapsed' ) ) { | |||
$toggleLink.text( showText ); | |||
} else { | |||
$toggleLink.text( hideText ); | |||
} | |||
// Stop table sorting activating when clicking the link | |||
e.stopPropagation(); | |||
} ); | |||
$collapsible.data( 'made-collapsible', true ); | |||
} ); | |||
}() ); | |||
/** | |||
* Задать минимальную высоту для анимированных элементов, чтобы предотвратить | |||
* «дёргание» страницы при различии высот фреймов | |||
*/ | |||
( function() { | |||
// Показать все фреймы, чтобы можно было измерить высоту | |||
var $animated = $wikipageContent.find( '.animated' ).addClass( 'animated-visible' ); | |||
// Сгруппировать фреймы по последовательностям | |||
var animateds = []; | |||
$animated.each( function() { | |||
animateds.push( { | |||
$: $( this ).find( '> .animated-subframe' ).addBack() | |||
.find( '> *:not(.animated-subframe)' ), | |||
} ); | |||
} ); | |||
// Найти самый высокий фрейм для каждой анимированной последовательности | |||
// (в случае, если высоты разные) | |||
$.each( animateds, function() { | |||
var minHeight = 0, differentHeights; | |||
this.$.each( function() { | |||
var height = this.offsetHeight; | |||
differentHeights = differentHeights || minHeight && height !== minHeight; | |||
minHeight = Math.max( height, minHeight ); | |||
} ); | |||
if ( differentHeights ) { | |||
this.height = minHeight; | |||
} | |||
} ); | |||
// Задать минимальную высоту контейнера анимации, не меньшую, чем у самого | |||
// высокого фрейма, и спрятать неактивные фреймы обратно | |||
$animated.each( function( i ) { | |||
$( this ).css( 'min-height', animateds[i].height ); | |||
} ).removeClass( 'animated-visible' ); | |||
// Прогружает все изображения в анимированном элементе сразу по появлении анимированного содержимого | |||
var animatedObserver = new IntersectionObserver( function( entries ) { | |||
entries.forEach( function( entry ) { | |||
if ( entry.isIntersecting && !entry.target.classList.contains( 'animated-lazyloaded' ) ) { | |||
$( entry.target ).find( 'img' ).attr( 'loading', 'eager' ); | |||
entry.target.classList.add( 'animated-lazyloaded' ); | |||
animatedObserver.unobserve( entry.target ); | |||
} | |||
} ); | |||
} ); | |||
// Задать наблюдатель для каждого анимированного элемента | |||
$( '.animated' ).each( function() { | |||
animatedObserver.observe(this); | |||
} ); | |||
}() ); | |||
/** | |||
* Page loader | |||
* | |||
* Allows a page to be downloaded and displayed on demand. | |||
* Use with Template:LoadPage and Template:LoadBox | |||
*/ | |||
( function() { | |||
var $loadPage = $wikipageContent.find( '.load-page' ); | |||
if ( !$loadPage.length ) { | |||
return; | |||
} | |||
// We need the spinner to show loading is happening, but we don't want | |||
// to have a delay while the module downloads, so we'll load this now, | |||
// regardless of if something is clicked | |||
mw.loader.load( 'jquery.spinner' ); | |||
// Create button starting with hide text | |||
// Will be changed to the show text while calculating the maximum button size | |||
var $buttonTemplate = $( '<span>' ).addClass( 'mw-editsection-like load-page-button' ) | |||
.append( '[', $( '<span>' ).addClass( 'jslink' ).text( i18n.hideText ), ']' ); | |||
var extractList = function( $contentContainer, listClass ) { | |||
var $content = $contentContainer.find( '.mw-parser-output > ul > li > ul' ).children( ':not(.nbttree-inherited)' ); | |||
if ( listClass ) { | |||
$content.addClass( listClass ); | |||
} | |||
return $content; | |||
}; | |||
$loadPage.each( function() { | |||
var $body = $( this ); | |||
var page = $body.data( 'page' ); | |||
if ( !page ) { | |||
return; | |||
} | |||
var template = $body.data( 'template' ); | |||
var treeview = $body.data( 'treeview' ); | |||
var treeviewClass = $body.data( 'treeviewclass' ); | |||
var $heading; | |||
var $contentContainer; | |||
var $content; | |||
var $button = $buttonTemplate.clone(); | |||
var $buttonLink = $button.find( '.jslink' ); | |||
if ( treeview ) { | |||
$heading = $body; | |||
$contentContainer = $( '<div>' ); | |||
} else { | |||
$heading = $body.children().first(); | |||
$contentContainer = $body.find( '.load-page-content' ); | |||
} | |||
// Add the button | |||
$heading.append( $button ); | |||
// Move the edit button to the right spot | |||
$contentContainer.find( '.mw-editsection, .mw-editsection-like' ).insertAfter( $button ); | |||
// Find max button width, and set its min-width to it | |||
var hideWidth = $button.width(); | |||
$buttonLink.text( i18n.showText ); | |||
var showWidth = $button.width(); | |||
if ( hideWidth !== showWidth ) { | |||
$button.css( 'min-width', hideWidth > showWidth ? hideWidth : showWidth ); | |||
} | |||
$buttonLink.click( function() { | |||
if ( $body.hasClass( 'pageloader-contentloaded' ) ) { | |||
if ( $buttonLink.text() === i18n.showText ) { | |||
if ( treeview ) { | |||
$content.insertAfter( $body ); | |||
} else { | |||
$contentContainer.show(); | |||
} | |||
$buttonLink.text( i18n.hideText ); | |||
} else { | |||
if ( treeview ) { | |||
$content.detach(); | |||
} else { | |||
$contentContainer.hide(); | |||
} | |||
$buttonLink.text( i18n.showText ); | |||
} | |||
return; | |||
} | |||
// See if this was loaded elsewhere before making a request | |||
var gotContent; | |||
$( '.pageloader-contentloaded' ).each( function() { | |||
var $fLoader = $( this ); | |||
if ( $fLoader.data( 'page' ) === page && $fLoader.data( 'mw-pageloader-content' ) ) { | |||
$contentContainer.html( $fLoader.data( 'mw-pageloader-content' ) ).removeClass( 'noscript' ); | |||
mw.hook( 'wikipage.content' ).fire( $contentContainer ); | |||
if ( treeview ) { | |||
$body.find( '.noscript' ).remove(); | |||
$content = extractList( $contentContainer, treeviewClass ); | |||
$content.insertAfter( $body ); | |||
} | |||
$buttonLink.text( i18n.hideText ); | |||
$body.addClass( 'pageloader-contentloaded' ); | |||
gotContent = true; | |||
return false; | |||
} | |||
} ); | |||
if ( gotContent ) { | |||
return; | |||
} | |||
// Just in-case the spinner module is still not ready yet | |||
var $spinner = $(); | |||
mw.loader.using( 'jquery.spinner', function() { | |||
// $spinner will be false if the content somehow loaded before the module did | |||
if ( $spinner ) { | |||
$spinner = $.createSpinner().addClass( 'mw-editsection-like' ) | |||
.css( 'min-width', $button.css( 'min-width' ) ); | |||
$button.hide().after( $spinner ); | |||
} | |||
} ); | |||
var requestData = { | |||
action: 'parse', | |||
prop: 'text' | |||
}; | |||
if ( template ) { | |||
requestData.page = page; | |||
} else { | |||
requestData.title = mw.config.get( 'wgPageName' ); | |||
requestData.text = '{' + '{:' + page + '}}'; | |||
} | |||
new mw.Api().get( requestData ).done( function( data ) { | |||
var html = data.parse.text['*']; | |||
$contentContainer.html( html ).removeClass( 'noscript' ); | |||
// Resolve self-links | |||
if ( template ) { | |||
var curPage = '/' + mw.config.get( 'wgPageName' ); | |||
$contentContainer.find( 'a' ).each( function() { | |||
var $link = $( this ); | |||
if ( $link.attr( 'href' ) === curPage ) { | |||
$link.replaceWith( $( '<strong>' ).addClass( 'selflink' ).append( $link.contents() ) ); | |||
} | |||
} ); | |||
html = $contentContainer.html(); | |||
} | |||
$body.data( 'mw-pageloader-content', html ); | |||
// Fire content hook on the new content, running all this stuff again and more :) | |||
mw.hook( 'wikipage.content' ).fire( $contentContainer ); | |||
if ( treeview ) { | |||
$body.find( '.noscript' ).remove(); | |||
$content = extractList( $contentContainer, treeviewClass ); | |||
$content.insertAfter( $body ); | |||
} | |||
$spinner.remove(); | |||
$spinner = false; | |||
$buttonLink.text( i18n.hideText ); | |||
$button.show(); | |||
$body.addClass( 'pageloader-contentloaded' ); | |||
} ).fail( function( _, error ) { | |||
$spinner.remove(); | |||
$spinner = false; | |||
$button.show(); | |||
var errorText = ''; | |||
if ( error.textStatus ) { | |||
errorText = error.textStatus; | |||
} else if ( error.error ) { | |||
errorText = error.error.info; | |||
} | |||
mw.notify( errorText, { title: i18n.loadErrorTitle, autoHide: false } ); | |||
} ); | |||
} ); | |||
} ); | |||
}() ); | |||
/* Добавляет виджет Discord на портал сообщества */ | |||
$('#portal-discord-widget').html($('<iframe>') | |||
.attr('class', 'discord-widget discord-widget-dark') | |||
.attr('src', 'https://discord.com/widget?id=343694556522479616&theme=dark') | |||
.attr('width', '350') | |||
.attr('height', '500') | |||
.attr('allowtransparency', 'true') | |||
.attr('frameborder', '0') | |||
); | |||
} ); | |||
/* Конец скрипта, действующего для вики-содержимого */ | |||
/* Активируется по готовности объектной модели документа (DOM) */ | |||
$( function() { | |||
/** | |||
* Реализация анимированных элементов | |||
* | |||
* Сценарий прокручивает каждые 2 секунды множество элементов (фреймов) внутри | |||
* HTML-элемента с классом animated. Первый фрейм может быть задан с помощью | |||
* класса animated-active. | |||
* | |||
* Фрейм может быть контейнером подфреймов, если для него задан класс | |||
* animated-subframe; для одного из подфреймов нужно задать animated-active. | |||
* Подфреймы будут прокручиваться только после прокрутки последовательности | |||
* фреймов 1-го порядка (подробнее в документации к шаблону «Инвентарный слот»). | |||
* | |||
* Если у анимированного элемента класс animated-paused, то он не будет про- | |||
* кручиваться. Обычно класс добавляется и снимается при наведении или снятии | |||
* курсора мыши (см. ниже). | |||
*/ | |||
( function() { | |||
var $content = $( '#mw-content-text' ); | |||
var advanceFrame = function( parentElem, parentSelector ) { | |||
var curFrame = parentElem.querySelector( parentSelector + ' > .animated-active' ); | |||
$( curFrame ).removeClass( 'animated-active' ); | |||
var $nextFrame = $( curFrame && curFrame.nextElementSibling || parentElem.firstElementChild ); | |||
return $nextFrame.addClass( 'animated-active' ); | |||
}; | |||
// Задаёт название скрытого свойства | |||
var hidden; | |||
if ( typeof document.hidden !== 'undefined' ) { | |||
hidden = 'hidden'; | |||
} else if ( typeof document.msHidden !== 'undefined' ) { | |||
hidden = 'msHidden'; | |||
} else if ( typeof document.webkitHidden !== 'undefined' ) { | |||
hidden = 'webkitHidden'; | |||
} | |||
setInterval( function() { | |||
if ( hidden && document[hidden] ) { | |||
return; | |||
} | |||
$content.find( '.animated' ).each( function() { | |||
if ( $( this ).hasClass( 'animated-paused' ) ) { | |||
return; | |||
} | |||
var $nextFrame = advanceFrame( this, '.animated' ); | |||
if ( $nextFrame.hasClass( 'animated-subframe' ) ) { | |||
advanceFrame( $nextFrame[0], '.animated-subframe' ); | |||
} | |||
} ); | |||
}, 2000 ); | |||
}() ); | |||
/** | |||
* Fix edit summary prompt for undo | |||
* | |||
* Fixes the fact that the undo function combined with the "no edit summary prompter" | |||
* causes problems if leaving the edit summary unchanged. | |||
* Added by [[wikipedia:User:Deskana]], code by [[wikipedia:User:Tra]]. | |||
* See https://bugzilla.wikimedia.org/show_bug.cgi?id=8912 | |||
*/ | |||
if ( document.location.search.indexOf( "undo=" ) !== -1 && document.getElementsByName( 'wpAutoSummary' )[0] ) { | |||
document.getElementsByName( 'wpAutoSummary' )[0].value='1'; | |||
} | |||
/** | |||
* Останавливает анимации в пределах определённых контейнеров (элементов с | |||
* классом animated-container, а также отображений интерфейса обработчиков). | |||
* | |||
* Это помогает читателям подробнее всмотреться в изображения и перейти к | |||
* интересующим их страницам. | |||
*/ | |||
$( '#mw-content-text' ).on( | |||
'mouseenter mouseleave', | |||
'.animated-container, .grid-generic, .grid-Crafting_Table, .grid-Furnace, .grid-Brewing_Stand, .mcui, .gui', | |||
function(e) { | |||
$( this ).find( '.animated' ).toggleClass( 'animated-paused', e.type === 'mouseenter' ); | |||
} | |||
); | |||
/** | |||
* Make simple search suggestions box separately styled | |||
*/ | |||
mw.loader.using( 'mediawiki.searchSuggest', function() { | |||
$( '.suggestions:first' ).addClass( 'searchbar' ); | |||
} ); | |||
/** | |||
* Set unlicensed as the default license on file pages | |||
* | |||
* That way the file will be categorised so someone can find a license for the file | |||
*/ | |||
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Upload' ) { | |||
if ( $( '#wpLicense' ).val() === '' ) { | |||
$( '#wpLicense' ).val( i18n.defaultLicense ); | |||
} | |||
/* mw.loader.using( 'mediawiki.special.upload', function() { | |||
var change = setInterval( function() { | |||
if ( licenseSelectorCheck ) { | |||
$( '#wpLicense' ).change(); | |||
clearInterval( change ); | |||
} | |||
}, 500 ); | |||
} );*/ | |||
} | |||
/** | |||
* Создаёт всплывающие подсказки в стиле Minecraft | |||
* | |||
* Заменяет обычную подсказку. Поддерживает коды форматирования Minecraft | |||
* (кроме k). Дополнительный текст поддерживает несколько строк (разбивается | |||
* косой чертой «/»). | |||
*/ | |||
( function() { | |||
var escapeChars = { '\\&': '&', '<': '<', '>': '>' }; | |||
var escape = function( text ) { | |||
// Сначала экранируем «\» "\" | |||
return text.replace( /\\\\/g, '\' ) | |||
.replace( /\\&|[<>]/g, function( char ) { return escapeChars[char]; } ); | |||
}; | |||
var $tooltip = $(); | |||
var $win = $( window ), winWidth, winHeight, width, height; | |||
$( '#mw-content-text' ).on( { | |||
'mouseenter.minetip': function( e ) { | |||
$tooltip.remove(); | |||
var $elem = $( this ), title = $elem.attr( 'data-minetip-title' ); | |||
if ( title === undefined ) { | |||
title = $elem.attr( 'title' ); | |||
if ( title !== undefined ) { | |||
title = $.trim( title.replace( /&/g, '\\&' ) ); | |||
$elem.attr( 'data-minetip-title', title ); | |||
} | |||
} | |||
// Заглавие либо не определено, либо содержит только код форматирования | |||
if ( title === undefined || title !== '' && title.replace( /&([0-9a-jl-qs-wr])/g, '' ) === '' ) { | |||
// Находим заголовок самого «глубокого» вложенного элемента | |||
var childElem = $elem[0], childTitle; | |||
do { | |||
if ( childElem.hasAttribute( 'title' ) ) { | |||
childTitle = childElem.title; | |||
} | |||
childElem = childElem.firstChild; | |||
} while( childElem && childElem.nodeType === 1 ); | |||
if ( childTitle === undefined ) { | |||
return; | |||
} | |||
// Добавляем заголовок вложенного элемента в конец, после | |||
// возможного кода форматирования | |||
if ( !title ) { | |||
title = ''; | |||
} | |||
title += $.trim( childTitle.replace( /&/g, '\\&' ) ); | |||
// Сохраняем полученное заглавие для последующего использования | |||
$elem.attr( 'data-minetip-title', title ); | |||
//если вместо названия ссылка на файл, то убираем данные о названии мода | |||
if ( title.charAt(4) === ':' ) { | |||
$elem.removeAttr( 'data-modinfo-text' ); | |||
} | |||
} | |||
if ( !$elem.data( 'minetip-ready' ) ) { | |||
// Удаляем атрибуты заголовка, чтобы стандартная подсказка не мешала | |||
$elem.find( '[title]' ).addBack().removeAttr( 'title' ); | |||
$elem.data( 'minetip-ready', true ); | |||
} | |||
if ( title === '' ) { | |||
return; | |||
} | |||
var content = '<span class="minetip-title">' + escape(title) + '&r</span>'; | |||
var description = $.trim( $elem.attr( 'data-minetip-text' ) ); | |||
var english = $.trim( $elem.attr( 'data-minetip-english' ) ) || | |||
$.trim( $elem.attr( 'data-minetip-lowtitle' ) ); | |||
var modinfo = $.trim( $elem.attr( 'data-modinfo-text' ) ); | |||
if ( description || english || modinfo ) { | |||
content += '<span class="minetip-description">'; | |||
if ( description ) { | |||
description = escape( description ).replace( /\\\//g, '/' ); | |||
content += description.replace( /\//g, '<br>' ) + '&r'; | |||
if (english || modinfo) { | |||
content += '<br>'; | |||
} | |||
} | |||
if ( english ) { | |||
content += '<span class="minetip-english">англ. &o' + escape(english) + '&r</span>'; | |||
if (modinfo) { | |||
content += '<br>'; | |||
} | |||
} | |||
if ( modinfo ) { | |||
content += '<span class="minetip-modinfo">' + escape(modinfo) + '&r</span>'; | |||
} | |||
content += '</span>'; | |||
} | |||
// Добавить классы для кодов форматирования Minecraft | |||
while ( content.search( /&[0-9a-jl-qs-w]/ ) > -1 ) { | |||
content = content.replace( /&([0-9a-jl-qs-w])(.*?)(&r|$)/g, '<span class="format-$1">$2</span>&r' ); | |||
} | |||
// Убрать сбросы форматирования | |||
content = content.replace( /&r/g, '' ); | |||
$tooltip = $( '<div id="minetip-tooltip">' ); | |||
$tooltip.html( content ).appendTo( 'body' ); | |||
// Кэширование текущих размеров окна и подсказки | |||
winWidth = $win.width(); | |||
winHeight = $win.height(); | |||
width = $tooltip.outerWidth( true ); | |||
height = $tooltip.outerHeight( true ); | |||
// Сымитировать движение мыши, чтобы разместить подсказку | |||
$elem.trigger( 'mousemove', e ); | |||
}, | |||
'mousemove.minetip': function( e, trigger ) { | |||
if ( !$tooltip.length ) { | |||
$( this ).trigger( 'mouseenter' ); | |||
return; | |||
} | |||
// Получить данные о событии от удалённого триггера | |||
e = trigger || e; | |||
// Получить положение мыши и добавить смещение по умолчанию | |||
var top = e.clientY - 34; | |||
var left = e.clientX + 14; | |||
// В случае выхода за правый край экрана идём налево от курсора | |||
if ( left + width > winWidth ) { | |||
left -= width + 36; | |||
} | |||
// В случае выхода и за левый край экрана идём вверх от курсора | |||
if ( left < 0 ) { | |||
left = 0; | |||
top -= height - 22; | |||
// Идём вниз от курсора, если слишком высоко | |||
if ( top < 0 ) { | |||
top += height + 47; | |||
} | |||
// Не выходить за верхний край экрана | |||
} else if ( top < 0 ) { | |||
top = 0; | |||
// Не выходить за нижний край экрана | |||
} else if ( top + height > winHeight ) { | |||
top = winHeight - height; | |||
} | |||
// Применить расположение | |||
$tooltip.css( { top: top, left: left } ); | |||
}, | |||
'mouseleave.minetip': function() { | |||
if ( !$tooltip.length ) { | |||
return; | |||
} | |||
$tooltip.remove(); | |||
$tooltip = $(); | |||
} | |||
}, '.minetip, .grid > .item, .invslot-item' ); | |||
}() ); | |||
/* [[Шаблон:Проблемы с объектом]] */ | |||
mw.hook( 'wikipage.content' ).add( function( $content ) { | |||
$content.find('.issue-list').each( function() { | |||
let issueList = $(this); | |||
let apiRequests = []; | |||
for (let project in this.dataset) { | |||
let url = new URL('https://tools.minecraft.wiki/jigsaw/mojira'); | |||
url.searchParams.set('project', project.toUpperCase()); | |||
url.searchParams.set('jql', this.dataset[project]); | |||
delete this.dataset[project]; | |||
let apiRequest = $.ajax( url.href ); | |||
apiRequests.push( apiRequest.then( function( search ) { | |||
if ( search.errors ) return Promise.reject(search.errorMessages); | |||
let issueList = $('<ul>'); | |||
if ( search.issues.length ) { | |||
issueList.append( search.issues.map( function( issue ) { | |||
let issueLink = $('<a class="extiw">').attr('href', 'https://bugs.mojang.com/browse/' + issue.key).attr('title', 'mojira:' + issue.key).text(issue.key); | |||
return $('<li>').text(' – ' + ( issue.fields.resolution ? '[' + issue.fields.resolution.name + '] ' : '' ) + issue.fields.summary).prepend(issueLink); | |||
} ) ); | |||
if ( search.total > search.issues.length ) $('<li>').text( mw.format(i18n.more_results, search.total - search.issues.length) ).appendTo( issueList ); | |||
} | |||
else $('<li>').text( i18n.no_results ).appendTo( issueList ); | |||
return { project, list: issueList }; | |||
} ) ); | |||
} | |||
if ( apiRequests.length ) Promise.allSettled( apiRequests ).then( function( results ) { | |||
results.filter( result => result.status === 'rejected' ).forEach( result => console.warn('Mojira:', result.reason) ); | |||
if ( results.length === 1 ) { | |||
if ( results[0].status === 'fulfilled' ) issueList.append( results[0].value.list ); | |||
return; | |||
} | |||
issueList.append( | |||
results.filter( result => result.status === 'fulfilled' ).map( result => result.value ).flatMap( function( result ) { | |||
return [ | |||
$('<p>').append( $('<b>').text( i18n.projects[result.project] || result.project.toUpperCase() ) ), | |||
result.list | |||
]; | |||
} ) | |||
); | |||
} ); | |||
} ); | |||
} ); | |||
/** | |||
* API Purge | |||
* | |||
* Performs a purge with the API to avoid the confirmation form | |||
*/ | |||
mw.loader.using( 'mediawiki.api' ).then( function() { | |||
$( '#ca-purge a' ).on( 'click', function( e ) { | |||
new mw.Api().post( { | |||
action: 'purge', | |||
titles: mw.config.get( 'wgPageName' ) | |||
} ).then( function() { | |||
location.reload(); | |||
}, function() { | |||
mw.notify( 'Purge failed', { type: 'error' } ); | |||
} ); | |||
e.preventDefault(); | |||
} ); | |||
} ); | |||
} ); | |||
/* End DOM ready */ | |||
}() ); | |||
/* отключено до обновления визреда | |||
/ / Кнопки быстрого описания правки для визуального редактора | |||
mw.hook( 've.activationComplete' ).add( function () { | |||
mw.loader.load( 'ext.gadget.SummaryButtons' ); | |||
console.log('MediaWiki:Common.js — addSummaryBittons enabled'); | |||
} ); | |||
*/ |
Текущая версия от 14:58, 30 апреля 2025
/* Размещённый здесь код JavaScript будет загружаться пользователям при обращении к каждой странице */
mw.loader.load('/index.php?title=MediaWiki:ServerOnline.js&action=raw&ctype=text/javascript');
( function() {
'use strict';
/* Переменные для текста в интерфейсе, используюемые в сценарии и выделенные для удобства перевода */
var i18n = {
// Скрываемые элементы, подгрузка страниц
hideText: 'скрыть',
showText: 'показать',
// Подгрузка страниц
loadErrorTitle: 'Возникла ошибка при загрузке содержимого',
// Загрузка файлов
defaultLicense: 'Лицензия',
more_results: 'И ещё $1 нерешённых проблем.',
no_results: 'Активных отчётов не обнаружено.',
projects: {
bds: 'Bedrock Dedicated Server',
mc: 'Java Edition',
mcd: 'Minecraft Dungeons',
mcl: 'Лаунчер',
mclg: 'Minecraft Legends',
mcpe: 'Bedrock Edition',
realms: 'Realms',
web: 'Веб-сервисы Mojang'
}
};
/*
* Чтобы не захламлять глобальную область имён переменными, они должны быть
* добавлены в качестве свойства данной глобальной переменной.
*
* Например, вместо
* myVar = 'blah';
* используйте
* mcw.myVar = 'blah';
*/
var mcw = window.mcw = {};
/* Скрывает вкладки "Править вики-текст", "Просмотреть вики-текст", "Править" если им не хватает места в навигации */
$("li[id*='ca-watch']").addClass('collapsible');
$("li[id*='ca-unwatch']").addClass('collapsible');
$("li[id*='ca-edit']").addClass('collapsible');
$("li[id*='ca-view']").addClass('collapsible');
$("li[id*='ca-ve-edit']").addClass('collapsible');
$("li[id*='ca-viewsource']").addClass('collapsible');
/* Keep track of delegated events on dynamic content */
mcw.events = {};
/* Активируется при добавлении содержимого страниц вики (#mw-content-text, динамически загружаемое содержимое и т. д.) */
mw.hook( 'wikipage.content' ).add( function( $wikipageContent ) {
/**
* Collapsible elements
*
* Add the "collapsible" class to an element and the child element with class "collapsible-content"
* (or everything but the header row if a table) will be hidden when the element is collapsed.
*
* * Add the class "collapsed" to the element to make it start out collapsed.
* * Add either "collapsetoggle-left" or "collapsetoggle-inline" to the element to choose the collapse
* toggle alignment (defaults to right).
* * Add an ID in the format of "collapsible-<x>" to the element to make any element with the class
* "collapsetoggle-custom" and a matching class in the format of "collapsible-<x>-toggle" control
* the collapsing instead of the standard button.
* If the custom toggle contains an element with the "jslink" class, only that will be clickable.
*/
( function() {
var $collapsibles = $wikipageContent.find( '.collapsible' );
if ( !$collapsibles.length ) {
return;
}
var $toggleTemplate = $( '<span>' ).addClass( 'collapsetoggle' ).append(
'[', $( '<span>' ).addClass( 'jslink' ), ']'
);
$collapsibles.each( function() {
var $collapsible = $( this );
if ( $collapsible.data( 'made-collapsible' ) ) {
return true;
}
var $children = $collapsible.children();
var showText = $collapsible.data( 'expandtext' ) || i18n.showText;
var hideText = $collapsible.data( 'collapsetext' ) || i18n.hideText;
// If there is no content area, add it
if ( !$collapsible.is( 'table' ) && !$children.filter( '.collapsible-content' ).length ) {
if ( $collapsible.is( 'tr.collapsible-rows' ) ) {
var $collapsibleRows = $collapsible.nextUntil( '.collapsible-rows' );
if ( $collapsibleRows.hasClass( 'collapsible-row' ) ) {
$collapsibleRows = $collapsibleRows.filter( 'collapsible-row' );
} else {
$collapsibleRows.addClass( 'collapsible-row' );
}
if ( $collapsible.hasClass( 'collapsed' ) && !$collapsibleRows.hasClass( 'collapsed' ) ) {
$collapsibleRows.addClass( 'collapsed' );
}
$collapsible = $collapsible.add( $collapsibleRows );
} else if ( $collapsible.is( 'tr' ) ) {
$children.addClass( 'collapsible-content' );
} else {
$collapsible.wrapInner( '<div class="collapsible-content">' );
}
}
var $toggle;
var id = $collapsible.attr( 'id' );
if ( id && id.match( /^collapsible-./ ) ) {
$toggle = $( $wikipageContent[0].getElementsByClassName( id + '-toggle' ) )
.filter( '.collapsetoggle-custom' ).css( 'visibility', 'visible' );
}
// Create and insert the toggle button if there is no custom one
if ( !$toggle || !$toggle.length ) {
var $toggleContainer;
if ( $collapsible.is( 'table' ) ) {
var $rows = $children.filter( 'thead' ).children();
if ( !$rows.length ) {
$rows = $children.filter( 'tbody' ).first().children();
if ( !$rows.length ) {
$rows = $children.filter( 'tr' );
}
}
$toggleContainer = $rows.first().children().last();
} else {
$toggleContainer = $children.first();
if ( $toggleContainer.hasClass( 'collapsible-content' ) ) {
$toggleContainer = $collapsible;
}
}
$toggle = $toggleTemplate.clone();
if ( $collapsible.hasClass( 'collapsetoggle-inline' ) || $collapsible.hasClass( 'collapse-button-none' ) ) {
$toggleContainer.append( $toggle );
} else {
$toggleContainer.prepend( $toggle );
}
}
var $toggleLink = $toggle.find( '.jslink' );
if ( !$toggleLink.length ) {
$toggleLink = $toggle;
}
$toggleLink.attr( 'tabindex', 0 ).text( hideText );
// Find max toggle size, and set its min-width to it
var hideWidth = $toggle.width();
$toggleLink.text( showText );
var showWidth = $toggle.width();
if ( hideWidth !== showWidth ) {
$toggle.css( 'min-width', hideWidth > showWidth ? hideWidth : showWidth );
}
// Set the text back to hide if it's not collapsed to begin with
if ( !$collapsible.first().hasClass( 'collapsed' ) ) {
$toggleLink.text( hideText );
}
$toggleLink.on( 'click keydown', function( e ) {
// Only trigger on enter press
if ( e.keyCode && e.keyCode !== 13 ) {
return;
}
// Don't toggle when clicking buttons or links inside the toggle
var $target = $( e.target );
if ( $target.is( 'button' ) || $target.is( 'a' ) ) {
return;
}
$collapsible.toggleClass( 'collapsed' );
if ( $collapsible.first().hasClass( 'collapsed' ) ) {
$toggleLink.text( showText );
} else {
$toggleLink.text( hideText );
}
// Stop table sorting activating when clicking the link
e.stopPropagation();
} );
$collapsible.data( 'made-collapsible', true );
} );
}() );
/**
* Задать минимальную высоту для анимированных элементов, чтобы предотвратить
* «дёргание» страницы при различии высот фреймов
*/
( function() {
// Показать все фреймы, чтобы можно было измерить высоту
var $animated = $wikipageContent.find( '.animated' ).addClass( 'animated-visible' );
// Сгруппировать фреймы по последовательностям
var animateds = [];
$animated.each( function() {
animateds.push( {
$: $( this ).find( '> .animated-subframe' ).addBack()
.find( '> *:not(.animated-subframe)' ),
} );
} );
// Найти самый высокий фрейм для каждой анимированной последовательности
// (в случае, если высоты разные)
$.each( animateds, function() {
var minHeight = 0, differentHeights;
this.$.each( function() {
var height = this.offsetHeight;
differentHeights = differentHeights || minHeight && height !== minHeight;
minHeight = Math.max( height, minHeight );
} );
if ( differentHeights ) {
this.height = minHeight;
}
} );
// Задать минимальную высоту контейнера анимации, не меньшую, чем у самого
// высокого фрейма, и спрятать неактивные фреймы обратно
$animated.each( function( i ) {
$( this ).css( 'min-height', animateds[i].height );
} ).removeClass( 'animated-visible' );
// Прогружает все изображения в анимированном элементе сразу по появлении анимированного содержимого
var animatedObserver = new IntersectionObserver( function( entries ) {
entries.forEach( function( entry ) {
if ( entry.isIntersecting && !entry.target.classList.contains( 'animated-lazyloaded' ) ) {
$( entry.target ).find( 'img' ).attr( 'loading', 'eager' );
entry.target.classList.add( 'animated-lazyloaded' );
animatedObserver.unobserve( entry.target );
}
} );
} );
// Задать наблюдатель для каждого анимированного элемента
$( '.animated' ).each( function() {
animatedObserver.observe(this);
} );
}() );
/**
* Page loader
*
* Allows a page to be downloaded and displayed on demand.
* Use with Template:LoadPage and Template:LoadBox
*/
( function() {
var $loadPage = $wikipageContent.find( '.load-page' );
if ( !$loadPage.length ) {
return;
}
// We need the spinner to show loading is happening, but we don't want
// to have a delay while the module downloads, so we'll load this now,
// regardless of if something is clicked
mw.loader.load( 'jquery.spinner' );
// Create button starting with hide text
// Will be changed to the show text while calculating the maximum button size
var $buttonTemplate = $( '<span>' ).addClass( 'mw-editsection-like load-page-button' )
.append( '[', $( '<span>' ).addClass( 'jslink' ).text( i18n.hideText ), ']' );
var extractList = function( $contentContainer, listClass ) {
var $content = $contentContainer.find( '.mw-parser-output > ul > li > ul' ).children( ':not(.nbttree-inherited)' );
if ( listClass ) {
$content.addClass( listClass );
}
return $content;
};
$loadPage.each( function() {
var $body = $( this );
var page = $body.data( 'page' );
if ( !page ) {
return;
}
var template = $body.data( 'template' );
var treeview = $body.data( 'treeview' );
var treeviewClass = $body.data( 'treeviewclass' );
var $heading;
var $contentContainer;
var $content;
var $button = $buttonTemplate.clone();
var $buttonLink = $button.find( '.jslink' );
if ( treeview ) {
$heading = $body;
$contentContainer = $( '<div>' );
} else {
$heading = $body.children().first();
$contentContainer = $body.find( '.load-page-content' );
}
// Add the button
$heading.append( $button );
// Move the edit button to the right spot
$contentContainer.find( '.mw-editsection, .mw-editsection-like' ).insertAfter( $button );
// Find max button width, and set its min-width to it
var hideWidth = $button.width();
$buttonLink.text( i18n.showText );
var showWidth = $button.width();
if ( hideWidth !== showWidth ) {
$button.css( 'min-width', hideWidth > showWidth ? hideWidth : showWidth );
}
$buttonLink.click( function() {
if ( $body.hasClass( 'pageloader-contentloaded' ) ) {
if ( $buttonLink.text() === i18n.showText ) {
if ( treeview ) {
$content.insertAfter( $body );
} else {
$contentContainer.show();
}
$buttonLink.text( i18n.hideText );
} else {
if ( treeview ) {
$content.detach();
} else {
$contentContainer.hide();
}
$buttonLink.text( i18n.showText );
}
return;
}
// See if this was loaded elsewhere before making a request
var gotContent;
$( '.pageloader-contentloaded' ).each( function() {
var $fLoader = $( this );
if ( $fLoader.data( 'page' ) === page && $fLoader.data( 'mw-pageloader-content' ) ) {
$contentContainer.html( $fLoader.data( 'mw-pageloader-content' ) ).removeClass( 'noscript' );
mw.hook( 'wikipage.content' ).fire( $contentContainer );
if ( treeview ) {
$body.find( '.noscript' ).remove();
$content = extractList( $contentContainer, treeviewClass );
$content.insertAfter( $body );
}
$buttonLink.text( i18n.hideText );
$body.addClass( 'pageloader-contentloaded' );
gotContent = true;
return false;
}
} );
if ( gotContent ) {
return;
}
// Just in-case the spinner module is still not ready yet
var $spinner = $();
mw.loader.using( 'jquery.spinner', function() {
// $spinner will be false if the content somehow loaded before the module did
if ( $spinner ) {
$spinner = $.createSpinner().addClass( 'mw-editsection-like' )
.css( 'min-width', $button.css( 'min-width' ) );
$button.hide().after( $spinner );
}
} );
var requestData = {
action: 'parse',
prop: 'text'
};
if ( template ) {
requestData.page = page;
} else {
requestData.title = mw.config.get( 'wgPageName' );
requestData.text = '{' + '{:' + page + '}}';
}
new mw.Api().get( requestData ).done( function( data ) {
var html = data.parse.text['*'];
$contentContainer.html( html ).removeClass( 'noscript' );
// Resolve self-links
if ( template ) {
var curPage = '/' + mw.config.get( 'wgPageName' );
$contentContainer.find( 'a' ).each( function() {
var $link = $( this );
if ( $link.attr( 'href' ) === curPage ) {
$link.replaceWith( $( '<strong>' ).addClass( 'selflink' ).append( $link.contents() ) );
}
} );
html = $contentContainer.html();
}
$body.data( 'mw-pageloader-content', html );
// Fire content hook on the new content, running all this stuff again and more :)
mw.hook( 'wikipage.content' ).fire( $contentContainer );
if ( treeview ) {
$body.find( '.noscript' ).remove();
$content = extractList( $contentContainer, treeviewClass );
$content.insertAfter( $body );
}
$spinner.remove();
$spinner = false;
$buttonLink.text( i18n.hideText );
$button.show();
$body.addClass( 'pageloader-contentloaded' );
} ).fail( function( _, error ) {
$spinner.remove();
$spinner = false;
$button.show();
var errorText = '';
if ( error.textStatus ) {
errorText = error.textStatus;
} else if ( error.error ) {
errorText = error.error.info;
}
mw.notify( errorText, { title: i18n.loadErrorTitle, autoHide: false } );
} );
} );
} );
}() );
/* Добавляет виджет Discord на портал сообщества */
$('#portal-discord-widget').html($('<iframe>')
.attr('class', 'discord-widget discord-widget-dark')
.attr('src', 'https://discord.com/widget?id=343694556522479616&theme=dark')
.attr('width', '350')
.attr('height', '500')
.attr('allowtransparency', 'true')
.attr('frameborder', '0')
);
} );
/* Конец скрипта, действующего для вики-содержимого */
/* Активируется по готовности объектной модели документа (DOM) */
$( function() {
/**
* Реализация анимированных элементов
*
* Сценарий прокручивает каждые 2 секунды множество элементов (фреймов) внутри
* HTML-элемента с классом animated. Первый фрейм может быть задан с помощью
* класса animated-active.
*
* Фрейм может быть контейнером подфреймов, если для него задан класс
* animated-subframe; для одного из подфреймов нужно задать animated-active.
* Подфреймы будут прокручиваться только после прокрутки последовательности
* фреймов 1-го порядка (подробнее в документации к шаблону «Инвентарный слот»).
*
* Если у анимированного элемента класс animated-paused, то он не будет про-
* кручиваться. Обычно класс добавляется и снимается при наведении или снятии
* курсора мыши (см. ниже).
*/
( function() {
var $content = $( '#mw-content-text' );
var advanceFrame = function( parentElem, parentSelector ) {
var curFrame = parentElem.querySelector( parentSelector + ' > .animated-active' );
$( curFrame ).removeClass( 'animated-active' );
var $nextFrame = $( curFrame && curFrame.nextElementSibling || parentElem.firstElementChild );
return $nextFrame.addClass( 'animated-active' );
};
// Задаёт название скрытого свойства
var hidden;
if ( typeof document.hidden !== 'undefined' ) {
hidden = 'hidden';
} else if ( typeof document.msHidden !== 'undefined' ) {
hidden = 'msHidden';
} else if ( typeof document.webkitHidden !== 'undefined' ) {
hidden = 'webkitHidden';
}
setInterval( function() {
if ( hidden && document[hidden] ) {
return;
}
$content.find( '.animated' ).each( function() {
if ( $( this ).hasClass( 'animated-paused' ) ) {
return;
}
var $nextFrame = advanceFrame( this, '.animated' );
if ( $nextFrame.hasClass( 'animated-subframe' ) ) {
advanceFrame( $nextFrame[0], '.animated-subframe' );
}
} );
}, 2000 );
}() );
/**
* Fix edit summary prompt for undo
*
* Fixes the fact that the undo function combined with the "no edit summary prompter"
* causes problems if leaving the edit summary unchanged.
* Added by [[wikipedia:User:Deskana]], code by [[wikipedia:User:Tra]].
* See https://bugzilla.wikimedia.org/show_bug.cgi?id=8912
*/
if ( document.location.search.indexOf( "undo=" ) !== -1 && document.getElementsByName( 'wpAutoSummary' )[0] ) {
document.getElementsByName( 'wpAutoSummary' )[0].value='1';
}
/**
* Останавливает анимации в пределах определённых контейнеров (элементов с
* классом animated-container, а также отображений интерфейса обработчиков).
*
* Это помогает читателям подробнее всмотреться в изображения и перейти к
* интересующим их страницам.
*/
$( '#mw-content-text' ).on(
'mouseenter mouseleave',
'.animated-container, .grid-generic, .grid-Crafting_Table, .grid-Furnace, .grid-Brewing_Stand, .mcui, .gui',
function(e) {
$( this ).find( '.animated' ).toggleClass( 'animated-paused', e.type === 'mouseenter' );
}
);
/**
* Make simple search suggestions box separately styled
*/
mw.loader.using( 'mediawiki.searchSuggest', function() {
$( '.suggestions:first' ).addClass( 'searchbar' );
} );
/**
* Set unlicensed as the default license on file pages
*
* That way the file will be categorised so someone can find a license for the file
*/
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Upload' ) {
if ( $( '#wpLicense' ).val() === '' ) {
$( '#wpLicense' ).val( i18n.defaultLicense );
}
/* mw.loader.using( 'mediawiki.special.upload', function() {
var change = setInterval( function() {
if ( licenseSelectorCheck ) {
$( '#wpLicense' ).change();
clearInterval( change );
}
}, 500 );
} );*/
}
/**
* Создаёт всплывающие подсказки в стиле Minecraft
*
* Заменяет обычную подсказку. Поддерживает коды форматирования Minecraft
* (кроме k). Дополнительный текст поддерживает несколько строк (разбивается
* косой чертой «/»).
*/
( function() {
var escapeChars = { '\\&': '&', '<': '<', '>': '>' };
var escape = function( text ) {
// Сначала экранируем «\» "\"
return text.replace( /\\\\/g, '\' )
.replace( /\\&|[<>]/g, function( char ) { return escapeChars[char]; } );
};
var $tooltip = $();
var $win = $( window ), winWidth, winHeight, width, height;
$( '#mw-content-text' ).on( {
'mouseenter.minetip': function( e ) {
$tooltip.remove();
var $elem = $( this ), title = $elem.attr( 'data-minetip-title' );
if ( title === undefined ) {
title = $elem.attr( 'title' );
if ( title !== undefined ) {
title = $.trim( title.replace( /&/g, '\\&' ) );
$elem.attr( 'data-minetip-title', title );
}
}
// Заглавие либо не определено, либо содержит только код форматирования
if ( title === undefined || title !== '' && title.replace( /&([0-9a-jl-qs-wr])/g, '' ) === '' ) {
// Находим заголовок самого «глубокого» вложенного элемента
var childElem = $elem[0], childTitle;
do {
if ( childElem.hasAttribute( 'title' ) ) {
childTitle = childElem.title;
}
childElem = childElem.firstChild;
} while( childElem && childElem.nodeType === 1 );
if ( childTitle === undefined ) {
return;
}
// Добавляем заголовок вложенного элемента в конец, после
// возможного кода форматирования
if ( !title ) {
title = '';
}
title += $.trim( childTitle.replace( /&/g, '\\&' ) );
// Сохраняем полученное заглавие для последующего использования
$elem.attr( 'data-minetip-title', title );
//если вместо названия ссылка на файл, то убираем данные о названии мода
if ( title.charAt(4) === ':' ) {
$elem.removeAttr( 'data-modinfo-text' );
}
}
if ( !$elem.data( 'minetip-ready' ) ) {
// Удаляем атрибуты заголовка, чтобы стандартная подсказка не мешала
$elem.find( '[title]' ).addBack().removeAttr( 'title' );
$elem.data( 'minetip-ready', true );
}
if ( title === '' ) {
return;
}
var content = '<span class="minetip-title">' + escape(title) + '&r</span>';
var description = $.trim( $elem.attr( 'data-minetip-text' ) );
var english = $.trim( $elem.attr( 'data-minetip-english' ) ) ||
$.trim( $elem.attr( 'data-minetip-lowtitle' ) );
var modinfo = $.trim( $elem.attr( 'data-modinfo-text' ) );
if ( description || english || modinfo ) {
content += '<span class="minetip-description">';
if ( description ) {
description = escape( description ).replace( /\\\//g, '/' );
content += description.replace( /\//g, '<br>' ) + '&r';
if (english || modinfo) {
content += '<br>';
}
}
if ( english ) {
content += '<span class="minetip-english">англ. &o' + escape(english) + '&r</span>';
if (modinfo) {
content += '<br>';
}
}
if ( modinfo ) {
content += '<span class="minetip-modinfo">' + escape(modinfo) + '&r</span>';
}
content += '</span>';
}
// Добавить классы для кодов форматирования Minecraft
while ( content.search( /&[0-9a-jl-qs-w]/ ) > -1 ) {
content = content.replace( /&([0-9a-jl-qs-w])(.*?)(&r|$)/g, '<span class="format-$1">$2</span>&r' );
}
// Убрать сбросы форматирования
content = content.replace( /&r/g, '' );
$tooltip = $( '<div id="minetip-tooltip">' );
$tooltip.html( content ).appendTo( 'body' );
// Кэширование текущих размеров окна и подсказки
winWidth = $win.width();
winHeight = $win.height();
width = $tooltip.outerWidth( true );
height = $tooltip.outerHeight( true );
// Сымитировать движение мыши, чтобы разместить подсказку
$elem.trigger( 'mousemove', e );
},
'mousemove.minetip': function( e, trigger ) {
if ( !$tooltip.length ) {
$( this ).trigger( 'mouseenter' );
return;
}
// Получить данные о событии от удалённого триггера
e = trigger || e;
// Получить положение мыши и добавить смещение по умолчанию
var top = e.clientY - 34;
var left = e.clientX + 14;
// В случае выхода за правый край экрана идём налево от курсора
if ( left + width > winWidth ) {
left -= width + 36;
}
// В случае выхода и за левый край экрана идём вверх от курсора
if ( left < 0 ) {
left = 0;
top -= height - 22;
// Идём вниз от курсора, если слишком высоко
if ( top < 0 ) {
top += height + 47;
}
// Не выходить за верхний край экрана
} else if ( top < 0 ) {
top = 0;
// Не выходить за нижний край экрана
} else if ( top + height > winHeight ) {
top = winHeight - height;
}
// Применить расположение
$tooltip.css( { top: top, left: left } );
},
'mouseleave.minetip': function() {
if ( !$tooltip.length ) {
return;
}
$tooltip.remove();
$tooltip = $();
}
}, '.minetip, .grid > .item, .invslot-item' );
}() );
/* [[Шаблон:Проблемы с объектом]] */
mw.hook( 'wikipage.content' ).add( function( $content ) {
$content.find('.issue-list').each( function() {
let issueList = $(this);
let apiRequests = [];
for (let project in this.dataset) {
let url = new URL('https://tools.minecraft.wiki/jigsaw/mojira');
url.searchParams.set('project', project.toUpperCase());
url.searchParams.set('jql', this.dataset[project]);
delete this.dataset[project];
let apiRequest = $.ajax( url.href );
apiRequests.push( apiRequest.then( function( search ) {
if ( search.errors ) return Promise.reject(search.errorMessages);
let issueList = $('<ul>');
if ( search.issues.length ) {
issueList.append( search.issues.map( function( issue ) {
let issueLink = $('<a class="extiw">').attr('href', 'https://bugs.mojang.com/browse/' + issue.key).attr('title', 'mojira:' + issue.key).text(issue.key);
return $('<li>').text(' – ' + ( issue.fields.resolution ? '[' + issue.fields.resolution.name + '] ' : '' ) + issue.fields.summary).prepend(issueLink);
} ) );
if ( search.total > search.issues.length ) $('<li>').text( mw.format(i18n.more_results, search.total - search.issues.length) ).appendTo( issueList );
}
else $('<li>').text( i18n.no_results ).appendTo( issueList );
return { project, list: issueList };
} ) );
}
if ( apiRequests.length ) Promise.allSettled( apiRequests ).then( function( results ) {
results.filter( result => result.status === 'rejected' ).forEach( result => console.warn('Mojira:', result.reason) );
if ( results.length === 1 ) {
if ( results[0].status === 'fulfilled' ) issueList.append( results[0].value.list );
return;
}
issueList.append(
results.filter( result => result.status === 'fulfilled' ).map( result => result.value ).flatMap( function( result ) {
return [
$('<p>').append( $('<b>').text( i18n.projects[result.project] || result.project.toUpperCase() ) ),
result.list
];
} )
);
} );
} );
} );
/**
* API Purge
*
* Performs a purge with the API to avoid the confirmation form
*/
mw.loader.using( 'mediawiki.api' ).then( function() {
$( '#ca-purge a' ).on( 'click', function( e ) {
new mw.Api().post( {
action: 'purge',
titles: mw.config.get( 'wgPageName' )
} ).then( function() {
location.reload();
}, function() {
mw.notify( 'Purge failed', { type: 'error' } );
} );
e.preventDefault();
} );
} );
} );
/* End DOM ready */
}() );
/* отключено до обновления визреда
/ / Кнопки быстрого описания правки для визуального редактора
mw.hook( 've.activationComplete' ).add( function () {
mw.loader.load( 'ext.gadget.SummaryButtons' );
console.log('MediaWiki:Common.js — addSummaryBittons enabled');
} );
*/