Welcome to Wargaming.net Wiki!

Difference between revisions of "User:XXN:na/wikilinker.js"

Jump to: navigation, search
Revision as of 16:23, 2 November 2016Latest revision as of 21:14, 25 September 2017 
25 intermediate revisions by the same user not shown
Line 1:Line 1:
?// Wiki Linker+// WikiLinker
?// Find link for selected text+// Add wikilinks for selected text which is a comma-separated or bulleted list
?// old version without stemmer https://ru.wikipedia.org/w/index.php?title=MediaWiki:Gadget-wikilinker.js&oldid=67851678+// https://wiki.wargaming.net/en/index.php?title=User:XXN:na/wl.js&action=history
?// ++
?// https://ru.wikipedia.org/wiki/%D0%A3%D1%87%D0%B0%D1%81%D1%82%D0%BD%D0%B8%D0%BA:Q-bit_array/Gadget-wikilinker.js+
  
?// Toolbar buttons 
  
?var addOldToolbarButton = function() {+if ( mw.config.get('wgAction')==='edit'||mw.config.get('wgAction')==='submit' ) {
? var $toolbar = $( '#gadget-toolbar' );+
? if ( !$toolbar.length ) {+
? $toolbar = $( '#wikiEditor-ui-toolbar' );+
? }+
? $( '<div>' )+
? .addClass( 'tool tool-button wikiEditor-toolbar-spritedButton' )+
? .attr( 'id', 'mw-editbutton-gadget-wikilinker' )+
? .attr( 'alt', 'Вики-ссыльщик' )+
? .attr( 'title', 'Вики-ссыльщик — подбирает вики-ссылку для выделенного слова или словосочетания' )+
? .css( 'background-image', 'url(//upload.wikimedia.org/wikipedia/commons/a/ad/Wikilinker_toolbar.png) ' )+
? .appendTo( $toolbar )+
? .on( 'click', WikiLinker );+
?};+
  
?var addNewToolbarButton = function() {+function addbullets() {
? $( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {+var text = document.getElementById('wpTextbox1');
? 'section': 'main',+selectedText0 = text.value.substring(text.selectionStart, text.selectionEnd);
? 'group': 'format',+modifiedText0 = text.value.substring(text.selectionStart, text.selectionEnd).replace(/(.+)\n/g, '* $1\n' );
? 'tools': {+
? 'wikilinker': {+
? label: 'Вики-ссыльщик — подбирает вики-ссылку для выделенного слова или словосочетания',+
? type: 'button',+
? icon: '//upload.wikimedia.org/wikipedia/commons/b/bd/Wikilinker.png',+
? action: {+
? type: 'callback',+
? execute: function() {+
? WikiLinker();+
? }+
? }+
? }+
? }+
? } );+
?};+
  
?if ( $.inArray( mw.config.get( 'wgAction' ), [ 'edit', 'submit' ] ) !== -1 ) {+text0 = text.value.replace(selectedText0, modifiedText0);
? mw.loader.using( [ 'user.options', 'jquery.textSelection' ], function () {+$("#wpTextbox1").val(text0);
? if ( mw.user.options.get( 'usebetatoolbar' ) === 1 ) {+
? if ( mw.user.options.get( 'showtoolbar' ) === 1 ) {+
? $.when(+
? mw.loader.using( 'ext.wikiEditor.toolbar' ),+
? $.ready+
? ).then( addNewToolbarButton );+
? }+
? } else {+
? mw.loader.using( 'mediawiki.action.edit', function() {+
? $( addOldToolbarButton );+
? } );+
? }+
? } );+
 } }
  
 +function wikilinker() {
 + var text = document.getElementById('wpTextbox1');
 +selectedText = text.value.substring(text.selectionStart, text.selectionEnd);
 +modifiedText = text.value.substring(text.selectionStart, text.selectionEnd).replace(/, /g, ']], [[' );
 +modifiedText = modifiedText.replace(/(.+)/g, '[[$1]]' );
  
?function WikiLinker() {+// https://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/
? +// I want to replace a variable with a variable – but as a rule in replace function we have to pass a regular exprssion
? var xmlhttp;+// so we cannot write string.replace(var1, var2);
? var CantWork = 'Сначала нужно выделить слово или словосочетание';+// we have to convert the var1 to a regular expression
? var requestTokens = 0;+
? var $wpTextbox1 = $( '#wpTextbox1' );+
? +
? var txt = $wpTextbox1.textSelection( 'getSelection' );+
? var startEndPos = $( '#wpTextbox1' ).textSelection( 'getCaretPosition', {+
? startAndEnd: true+
? } ),+
? startPos = startEndPos[0],+
? endPos = startEndPos[1];+
  
? // Trim selected text+var sRegExInput = new RegExp(selectedText, "g");
? while ( txt.slice( 0, 1 ) === ' ' ) {+text1 = text.value.replace(selectedText, modifiedText);
? txt = txt.slice( 1 );+$("#wpTextbox1").val(text1);
? startPos = startPos + 1;+}
? }+
? while ( txt.slice( -1 ) === ' ' ) {+
? txt = txt.slice( 0, -1 );+
? endPos = endPos - 1;+
? }+
? if ( txt === '' ) {+
? mw.notify( CantWork );+
? return;+
? }+
? if ( startEndPos[0] !== startPos || startEndPos[1] !== endPos ) {+
? $wpTextbox1.textSelection( 'setSelection', {+
? start: startPos,+
? end: endPos +
? } );+
? }+
  
? processText( txt );+function wikilinkbullist() {
 + var text = document.getElementById('wpTextbox1');
 +selectedText1 = text.value.substring(text.selectionStart, text.selectionEnd);
 +modifiedText1 = text.value.substring(text.selectionStart, text.selectionEnd).replace(/\*\s*(\w.+)\n/g, '* [[$1]]\n');
 +//modifiedText = modifiedText.replace(/\*(.+)/g, '*[[$1]]');
  
 +//var sRegExInput = new RegExp(selectedText1, "g");
 +text2 = text.value.replace(selectedText1, modifiedText1);
 +$("#wpTextbox1").val(text2);
 +}
  
? function processText ( txt ) {+//firstHeading
? var preparedText = txt+//wikiEditor-ui-toolbar
? .substr( 0, 100 )+document.getElementById('firstHeading').innerHTML+='<table><tr>\
? .replace( /[«»%'"]/g, '' )+<td align="center" colspan="2">\
? .replace( /[\s\-–—_!?\.,:;]+/g, ' ' )+<button type="button" onClick="addbullets()">Add bullets to vertical list</button>\
? .trim();+<button type="button" onClick="wikilinker()">Wikify selected text (comma-separated list)</button>\
? var requestTokens = preparedText.split( ' ' ).length;+<button type="button" onClick="wikilinkbullist()">Wikify bulleted list</button>\
? var url = mw.config.get( 'wgServer' ) + mw.config.get( 'wgScriptPath' ) + +</td></tr></table>';
? '/api.php?action=query&list=search&continue=' + +
? '&srlimit=5&srprop=&format=json&srsearch=' + encodeURIComponent( txt );+
? +
? loadXMLDoc( url );+
? }+
? +
? +
? function loadXMLDoc ( url ) {+
? xmlhttp = GetXmlHttpObject();+
? if ( xmlhttp === null ) {+
? mw.notify( 'Your browser does not support XMLHTTP!' );+
? return;+
? }+
? xmlhttp.onreadystatechange = stateChanged;+
? xmlhttp.open( 'GET', url, true );+
? xmlhttp.send( null );+
? }+
? +
? +
? function GetXmlHttpObject() {+
? if ( window.XMLHttpRequest ) {+
? // code for IE7+, Firefox, Chrome, Opera, Safari+
? return new XMLHttpRequest();+
? }+
? if ( window.ActiveXObject ) {+
? // code for IE6, IE5+
? return new ActiveXObject( 'Microsoft.XMLHTTP' );+
? }+
? return null;+
? }+
? +
? +
? // сравнение по длине строки, без учёта уточнения в скобках+
? // чтобы для "Категори*" выдавалось "Категория (значения)", а не "Классификация"+
? function compareStringLengths ( a, b ) {+
? a = a.replace( / \(.*\)/g, '' );+
? b = b.replace( / \(.*\)/g, '' );+
? +
? if ( a.length < b.length ) {+
? return -1;+
? }+
? if ( a.length > b.length ) {+
? return 1;+
? }+
? return 0;+
? }+
? +
? +
? function initialLower ( str ) {+
? return str.substr( 0, 1 ).toLowerCase() + str.substr( 1 );+
? }+
? +
? +
? function stateChanged() {+
? if ( xmlhttp.readyState === 4 ) {+
? if ( xmlhttp.status === 200 ) {+
? var resp = eval( '(' + xmlhttp.responseText + ')' );+
? +
? if ( typeof resp.query.search[0] !== 'undefined' ) {+
? +
? var pageName = resp.query.search[0].title;+
? +
? // если в запросе было только одно слово, то выбираем самое короткое название из первых трёх результатов+
? // чтобы для "Аглией" выдавалось "Англия", а не "Англиканство"+
? +
? if ( requestTokens === 1 ) {+
? var resar = [];+
? +
? for ( var j = 0; j <= 4; j++ ) {+
? if ( typeof resp.query.search[j] !== 'undefined' &&+
? txt.substr( 0, 3 ).toLowerCase() === resp.query.search[j].title.substr( 0, 3 ).toLowerCase()+
? ) {+
? resar.push( resp.query.search[j].title );+
? }+
? }+
? +
? resar.sort( compareStringLengths );+
? +
? if ( typeof resar[0] !== 'undefined' ) {+
? pageName = resar[0];+
? }+
? }+
? +
? // для "форумы" будет "[[форум]]ы", а не "[[форум|форумы]]"+
? if ( initialLower( txt.substr( 0, pageName.length ) ) === initialLower( pageName ) &&+
? pageName.length <= txt.length+
? ) {+
? txt = '[[' + txt.substr( 0, pageName.length ) + ']]' ++
? txt.substr( pageName.length, txt.length - pageName.length );+
? }+
? else {+
? txt = '[[' + pageName + '|' + txt + ']]'; +
? }+
? }+
? else {+
? txt = '[[' + '|' + txt + ']]';+
? }+
? +
? $( '#wpTextbox1' )+
? .textSelection( 'encapsulateSelection', {+
? peri: txt,+
? replace: true+
? } )+
? .textSelection( 'scrollToCaretPosition' )+
? .focus();+
? }+
? }+
? }+
 } }

Latest revision as of 21:14, 25 September 2017

// WikiLinker
// Add wikilinks for selected text which is a comma-separated or bulleted list
// https://wiki.wargaming.net/en/index.php?title=User:XXN:na/wl.js&action=history


if ( mw.config.get('wgAction')==='edit'||mw.config.get('wgAction')==='submit' ) {

function addbullets() {
var text = document.getElementById('wpTextbox1');
selectedText0 = text.value.substring(text.selectionStart, text.selectionEnd);
modifiedText0 = text.value.substring(text.selectionStart, text.selectionEnd).replace(/(.+)\n/g, '* $1\n' );

text0 = text.value.replace(selectedText0, modifiedText0);
$("#wpTextbox1").val(text0);	
}

function wikilinker() {
  var text = document.getElementById('wpTextbox1');
selectedText = text.value.substring(text.selectionStart, text.selectionEnd);
modifiedText = text.value.substring(text.selectionStart, text.selectionEnd).replace(/, /g, ']], [[' );
modifiedText = modifiedText.replace(/(.+)/g, '[[$1]]' );

// https://burnignorance.com/php-programming-tips/how-to-use-a-variable-in-replace-function-of-javascript/
// I want to replace a variable with a variable – but as a rule in replace function we have to pass a regular exprssion
// so we cannot write string.replace(var1, var2);
// we have to convert the var1 to a regular expression

var sRegExInput = new RegExp(selectedText, "g");
text1 = text.value.replace(selectedText, modifiedText);
$("#wpTextbox1").val(text1);	
}

function wikilinkbullist() {
  var text = document.getElementById('wpTextbox1');
selectedText1 = text.value.substring(text.selectionStart, text.selectionEnd);
modifiedText1 = text.value.substring(text.selectionStart, text.selectionEnd).replace(/\*\s*(\w.+)\n/g, '* [[$1]]\n');
//modifiedText = modifiedText.replace(/\*(.+)/g, '*[[$1]]');

//var sRegExInput = new RegExp(selectedText1, "g");
text2 = text.value.replace(selectedText1, modifiedText1);
$("#wpTextbox1").val(text2);	
}

//firstHeading
//wikiEditor-ui-toolbar
document.getElementById('firstHeading').innerHTML+='<table><tr>\
<td align="center" colspan="2">\
<button type="button" onClick="addbullets()">Add bullets to vertical list</button>\
<button type="button" onClick="wikilinker()">Wikify selected text (comma-separated list)</button>\
<button type="button" onClick="wikilinkbullist()">Wikify bulleted list</button>\
</td></tr></table>';
}