MediaWiki:Common.js: Difference between revisions

From Tygron Support wiki
Jump to navigation Jump to search
mNo edit summary
No edit summary
 
(71 intermediate revisions by 2 users not shown)
Line 1: Line 1:
/* Any JavaScript here will be loaded for all users on every page load. */
/* Any JavaScript here will be loaded for all users on every page load. */
/*Render protected emails*/
$( function() {
    var emunp = function( elems ) {
        for (var i=0; i<elems.length; i++) {
            if ( !(' '+elems[i].className+' ').match( / protected-email / ) ) continue;
            elems[i].className = elems[i].className.replace( 'protected-email', '' )
            elems[i].innerHTML = elems[i].getAttribute('data-u') + '@' + '<span class="protected-email-scrape">honeypot.</span>' +  elems[i].getAttribute('data-d');
        }
    }
    var bc = document.getElementById('bodyContent');
    emunp( bc.getElementsByTagName( 'span' ) );
} );


/* For every span, div, table, td, or th, if that element has the class "pops", then all anchor links (e.g. from [] or [[]] syntax) should  open in a new tab/window. */
/* For every span, div, table, td, or th, if that element has the class "pops", then all anchor links (e.g. from [] or [[]] syntax) should  open in a new tab/window. */
Line 21: Line 35:
/*Inject a search bar to filter elements in lists, where the list filterer template is used*/
/*Inject a search bar to filter elements in lists, where the list filterer template is used*/
$( function() {
$( function() {
     var filterFunction = function(searchterm) {
   
var searchterm = this.parentElement.getElementsByClassName('list-filterer-input')[0].value;
     var filterFunction = function(input) {
var searchtarget = this.parentElement.getElementsByClassName(this.getAttribute('data-list'));
    var searchterm = input.value;
var searchin = searchtarget.length>0?searchtarget:[this.parentElement.parentElement];
    var searchtarget = document.getElementById('mw-content-text').getElementsByClassName(input.getAttribute('data-list'));
var el = 'li';
    var searchin = searchtarget.length>0?searchtarget:[input.parentElement.parentElement];
var e = this.parentElement.getElementsByTagName(el);
       
    var el = 'ul';
         for ( var i=0;i<searchin.length;i++) {
         for ( var i=0;i<searchin.length;i++) {
var e = searchin[i].getElementsByTagName(el);
        var uls = searchin[i].getElementsByTagName(el);
             for ( var i=0;i<e.length;i++ ) {
             for ( var j=0;j<uls.length;j++ ) {
                if (e[i].title.includes(searchterm) || e[i].textContent.includes(searchterm) ) {
 
e[i].style.removeProperty('display');
              var show = false;
} else {
              var lis = uls[j].children;
e[i].style.display='none';
             
}
              for(var k = 0; k<lis.length; k++){
 
                  var lie = lis[k];
                  if (lie.title.toLowerCase().includes(searchterm.toLowerCase()) || lie.textContent.toLowerCase().includes(searchterm.toLowerCase()) ) {
              lie.style.removeProperty('display');
                      show=true;             
          } else {
              lie.style.display='none';                 
          }                   
              }
              if(uls[j].parentNode){
                  /*uls[j].parentNode.style.display= show? 'inherit':'none'; */
              }
             }
             }
}
    }
};
 
        localStorage['tygron-wiki-searchterm'] = searchterm;         
    };
 
     var s = document.getElementsByClassName('list-filterer');
     var s = document.getElementsByClassName('list-filterer');
     for ( var i=0; i<s.length; i++ ) {
     for ( var i=0; i<s.length; i++ ) {
       
         if (s[i].getAttribute('data-ready')) continue;
         if (s[i].getAttribute('data-ready')) continue;
           
         var input = document.createElement('input');
         var input = document.createElement('input');
         var button = document.createElement('input');
         var button = document.createElement('input');
 
         input.setAttribute('class', 'list-filterer-input ' +s[i].getAttribute('class'));
         input.setAttribute('class', 'list-filterer-input ' +s[i].getAttribute('class'));
         input.setAttribute('type', 'search');
         input.setAttribute('type', 'search');
         input.setAttribute('placeholder', s[i].getAttribute('data-placeholder'));
         input.setAttribute('placeholder', s[i].getAttribute('data-placeholder'));
input.setAttribute('data-list', s[i].getAttribute('data-list'));
 
         button.setAttribute('class', 'list-filterer-button ' +s[i].getAttribute('class'));
         button.setAttribute('class', 'list-filterer-button ' +s[i].getAttribute('class'));
         button.setAttribute('type', 'submit');
         button.setAttribute('type', 'submit');
         button.setAttribute('value', s[i].getAttribute('data-value'));
         button.setAttribute('value', s[i].getAttribute('data-value'));
if (s[i].getAttribute('data-list')) {
    if (s[i].getAttribute('data-list')) {
    button.setAttribute('data-list', s[i].getAttribute('data-list'));
        button.setAttribute('data-list', s[i].getAttribute('data-list'));
}
    }
    s[i].insertBefore(input, null);
    s[i].insertBefore(input, null);
    s[i].insertBefore(button, null);
    s[i].insertBefore(button, null);
input.onchange = filterFunction;
input.onchange = function() {filterFunction(input);};
button.onclick = filterFunction;
button.onclick = function() {filterFunction(input);};
         s[i].setAttribute('data-ready', 'ready');
         s[i].setAttribute('data-ready', 'ready');
         input.setAttribute('data-ready', 'ready');
         input.setAttribute('data-ready', 'ready');
         button.setAttribute('data-ready', 'ready');
         button.setAttribute('data-ready', 'ready');
        var searchTerm = localStorage['tygron-wiki-searchterm'];
        if(searchTerm){
            window.scrollTo(0, 0);
            input.value = searchTerm;
            filterFunction(input);
        }
     }
     }
} );
});




Line 101: Line 141:


/*Mediawiki editing rules enforcement*/
/*Mediawiki editing rules enforcement*/
var getAllPatternMatches = function(subject, pattern) {
$( function() {
    var results = [];
    var matches = subject.matchAll(pattern);console.log(matches);
    var match = null;
    while( match = matches.next() ) {
        results.push(match);
        break;
    }
    return results;
}
var getSurroundingText = function(subject, startIndex, length) {
    var buffer = 40
    var start = Math.max(0, startIndex-buffer);
    var end = Math.min(subject.length, startIndex+length+buffer);
    return subject.substring(start, end);
}


var rules = {'Avoid <br>': { 'regex': /(<br(\s[^>]*)*>(\s)*)+/ig, 'warning':'There is an instance of a manual <br>.'}};
var skipEditingCheck = '';
if ( !$('form.mw-editform' ).length) {
skipEditingCheck = true;
} else {
var checkEditingExcludes = ['MediaWiki:', 'Template:'];
for ( var i = 0; i < checkEditingExcludes.length; i++ ) {
if ( $('h1#firstHeading.firstHeading').text().indexOf( checkEditingExcludes[i]) >= 0) {
skipEditingCheck = 'Article in namespace ' + checkEditingExcludes[i];
break;
}
}
}
skipEditingCheck = 'Awaiting explicit activation';
if (skipEditingCheck) {
if ( skipEditingCheck !== true ) {
console.log( 'Skipping the editing style check: '+skipEditingCheck );
}
return;
}
var getAllPatternMatches = function(subject, pattern) {
var results = [];
var matches = subject.matchAll(pattern);
var match = null;
while( match = matches.next() ) {
if (match.done) {
break;
}
results.push(match.value);
}
return results;
};
var getSurroundingText = function(subject, startIndex, length) {
var buffer = 40
var start = Math.max(0, startIndex-buffer);
var end = Math.min(subject.length, startIndex+length+buffer);
return subject.substring(start, end);
};


console.log('below here is 150');
var getEditingRulesHits = function(content) {
var getRulesResults = function(content) {
var results = {};
    var results = {};
for (var ruleName in rules) {
    for (var ruleName in rules) {
var rule = rules[ruleName];
        var rule = rules[ruleName];
var newResults = [];
        var newResults = [];
if (rule['regex']) {
        if (rule['regex']) {
var newResults = getAllPatternMatches(content, rule['regex']);
            var newResults = getAllPatternMatches(content, rule['regex']);
}
        }
if ( newResults.length > 0 ) {
        if ( newResults.length > 0 ) {
for (var resultIndex in newResults) {
            results[ruleName] = newResults;
var result = newResults[resultIndex];
        }
result['surroundingText'] = getSurroundingText(content, result['index'], result[0].length);
    }
}
    return results;
results[ruleName] = newResults;
}
}
}
return results;
};


console.log('below here is 151');
var convertResultsToDom = function(results) {
var convertResultsToDom = function(results) {
if ( Object.values(results).length === 0 ) {
    var $output = $('<div class=\'editResults\'></div>');
return null;
    if ( Object.values(results).length > 0 ) {
}
        for (var resultName in results) {
var $output = $('<div></div>').addClass('editRulesResults');
            console.log(resultName);
if ( Object.values(results).length > 0 ) {
            var rule = rules[resultName];
for (var resultName in results) {
console.log('below here is 152');
var rule = rules[resultName];
            var text = rule['error'] ? rule['error'] : rule['warning'];
var text = rule['error'] ? rule['error'] : rule['warning'];
            $results = $('<div></div>');
$results = $('<div></div>')
            $results.append('<span class=\'editResultsHeader\'></span>').text(text);
.addClass('editRulesResult');
           
$results.append(
            var ruleResults = results[resultName];
$('<span></span>')
.addClass('editRulesResultHeader')
.text(text)
);
var ruleResults = results[resultName];
for (var resultIndex in ruleResults) {
var result = ruleResults[resultIndex];
var stringResult = result.surroundingText;
$results.append( $('<div></div>')
.addClass('editRulesResultEntry')
.text(stringResult)
);
}
$output.append($results);
}
}
return $output;
};


            for (var result in ruleResults) {
var addResultsToDom = function( results ) {
console.log('below here is 153');
var $dom = convertResultsToDom( results );
$('.editButtons').find('.editRulesResults').remove();
$('.editButtons').prepend( $dom );
};


                console.log(result);
var checkAndReportRules = function( content ) {
                var stringResult = getSurroundingText(content, result['index'], result[0].length);
var content = $('textarea').val();
 
var results = getEditingRulesHits( content );
                $results.append( $('<p></p>').text(stringResult) );
addResultsToDom( results );
            }
return Object.values(results).length;
            $output.append($results);
};
        }
    }
var addRulesOverrideCheckboxToDom = function(  ) {
console.log('below here is 154');
var $overrideCheckbox = $('#mw-editpage-watch').clone();
    return $output;
$overrideCheckbox.attr('id', 'mw-editpage-overridechecks');
}
$overrideCheckbox.find('#wpWatchThisWidget')
 
.attr('id','wpOverridCheckseWidget');
console.log('below here is 155');
$overrideCheckbox.find('input[type=\'checkbox\']')
var reportResults = function( results ) {
.attr('id','wpOverrideChecks')
    var $dom = convertResultsToDom( results );
.attr('name','wpOverrideChecks')
    $('.editButtons').find('.editResults').remove();
.prop( 'checked', false )
    $('.editButtons').prepend( $dom );
.removeAttr('accesskey');
    console.log($dom);
$overrideCheckbox.find('label')
}
.attr('for','wpOverrideChecks')
 
.text('Override editing styling checks');
console.log('below here is 156');
var checkAndReportResults = function() {
console.log($overrideCheckbox);
    var content = $('textarea').val();
removeRulesOverrideCheckboxFromDom();
    var results = getRulesResults( content );
$('#mw-editpage-watch').parent().find( '#mw-editpage-overridechecks' ).remove();
    reportResults( results );
$('#mw-editpage-watch').parent().append($overrideCheckbox);
}
};
 
var removeRulesOverrideCheckboxFromDom = function(  ) {
console.log('below here is 157');
$('#mw-editpage-watch').parent().find( '#mw-editpage-overridechecks' ).remove();
checkAndReportResults();
};
var submitCheckRules = function() {
var doSubmit = true
if ( $('#mw-editpage-overridechecks').find(':checked').length ===0 ) {
var content = $('textarea').val();
var results = getEditingRulesHits( content );
addResultsToDom( results );
doSubmit = Object.values(results).length === 0;
}
if (!doSubmit) {
addRulesOverrideCheckboxToDom();
}
return doSubmit;
};
var rules = {
'Avoid <br>': { 'regex': /(<br(\s[^>]*)*>(\s)*)+/ig, 'warning':'There is an instance of a manual <br>.'}
};
$('form.mw-editform').on('submit', function(){
var doSubmit = submitCheckRules();
console.log( 'Result from checking editing rules: '+doSubmit );
return doSubmit;
});
$('form.mw-editform').find('textarea').on('change input', function(){
removeRulesOverrideCheckboxFromDom();
});
console.log('Editing style checking enabled.');
});

Latest revision as of 14:00, 29 February 2024

/* Any JavaScript here will be loaded for all users on every page load. */

/*Render protected emails*/
$( function() {
    var emunp = function( elems ) {
        for (var i=0; i<elems.length; i++) {
            if ( !(' '+elems[i].className+' ').match( / protected-email / ) ) continue;
            elems[i].className = elems[i].className.replace( 'protected-email', '' )
            elems[i].innerHTML = elems[i].getAttribute('data-u') + '@' + '<span class="protected-email-scrape">honeypot.</span>' +  elems[i].getAttribute('data-d');
        }
    }

    var bc = document.getElementById('bodyContent');
    emunp( bc.getElementsByTagName( 'span' ) );
} );

/* For every span, div, table, td, or th, if that element has the class "pops", then all anchor links (e.g. from [] or [[]] syntax) should  open in a new tab/window. */
$( function() {
     var pops = function( elems ) {
         for (var i=0; i<elems.length; i++) {
             if ( !(' '+elems[i].className+' ').match( / pops / ) ) continue;
             var anchs = elems[i].getElementsByTagName('a');
             for (var j=0; j<anchs.length; j++) anchs[j].target = '_blank';
         }
     };
     var bc = document.getElementById('bodyContent');
     var tags = ['span', 'div', 'table', 'td', 'th'];
     for (var i=0; i<tags.length; i++) pops( bc.getElementsByTagName( tags[i] ) );
 } );





/*Inject a search bar to filter elements in lists, where the list filterer template is used*/
$( function() {
    
    var filterFunction = function(input) {
	    var searchterm = input.value;
	    var searchtarget = document.getElementById('mw-content-text').getElementsByClassName(input.getAttribute('data-list'));
	    var searchin = searchtarget.length>0?searchtarget:[input.parentElement.parentElement];
        
	    var el = 'ul';
        for ( var i=0;i<searchin.length;i++) {
	        var uls = searchin[i].getElementsByTagName(el);
            for ( var j=0;j<uls.length;j++ ) {

               var show = false;
               var lis = uls[j].children;
               
               for(var k = 0; k<lis.length; k++){

                   var lie = lis[k];
                   if (lie.title.toLowerCase().includes(searchterm.toLowerCase()) || lie.textContent.toLowerCase().includes(searchterm.toLowerCase()) ) {
		               lie.style.removeProperty('display');
                       show=true;               
		           } else {
		               lie.style.display='none';                  
		           }                    
               }
               if(uls[j].parentNode){
                   /*uls[j].parentNode.style.display= show? 'inherit':'none'; */ 
               }  
            }
	    }

        localStorage['tygron-wiki-searchterm'] = searchterm;           
    };

    var s = document.getElementsByClassName('list-filterer');
    for ( var i=0; i<s.length; i++ ) {
        
        if (s[i].getAttribute('data-ready')) continue;
            
        var input = document.createElement('input');
        var button = document.createElement('input');

        input.setAttribute('class', 'list-filterer-input ' +s[i].getAttribute('class'));
        input.setAttribute('type', 'search');
        input.setAttribute('placeholder', s[i].getAttribute('data-placeholder'));
		input.setAttribute('data-list', s[i].getAttribute('data-list'));

        button.setAttribute('class', 'list-filterer-button ' +s[i].getAttribute('class'));
        button.setAttribute('type', 'submit');
        button.setAttribute('value', s[i].getAttribute('data-value'));
	    if (s[i].getAttribute('data-list')) {
	        button.setAttribute('data-list', s[i].getAttribute('data-list'));
	    }
		
	    s[i].insertBefore(input, null);
	    s[i].insertBefore(button, null);
		input.onchange = function() {filterFunction(input);};
		button.onclick = function() {filterFunction(input);};
		
        s[i].setAttribute('data-ready', 'ready');
        input.setAttribute('data-ready', 'ready');
        button.setAttribute('data-ready', 'ready');

        var searchTerm = localStorage['tygron-wiki-searchterm'];
        if(searchTerm){
             window.scrollTo(0, 0);
             input.value = searchTerm;
             filterFunction(input);
        }
    }
});





/*Auto redirect (for template "Preview redirect")*/
if (autoRedirectDiv = document.getElementById('automaticRedirect')) {
    try {
        var targetForRedirect = autoRedirectDiv.getElementsByTagName('a')[0].href
        var timeForRedirect = (autoRedirectDiv.getElementsByClassName('timeToRedirect')[0].getInnerHTML())
    } catch (err) {
        console.error(err);
    }
    var intervalId = setInterval(function(){
        try {
            var targetForRedirect = autoRedirectDiv.getElementsByTagName('a')[0].href
            var timeForRedirect = (autoRedirectDiv.getElementsByClassName('timeToRedirect')[0].getInnerHTML())
            if (timeForRedirect <= 1 && timeForRedirect > 0) {
                (autoRedirectDiv.getElementsByClassName('timeToRedirect')[0].innerHTML = 0);
                console.log('redirecting to: '+targetForRedirect+' now.');
                window.location = targetForRedirect;
            } else {
                (autoRedirectDiv.getElementsByClassName('timeToRedirect')[0].innerHTML = timeForRedirect-1);
                console.log('redirecting to: '+targetForRedirect+' in '+timeForRedirect+' second(s).');
            }
        } catch (err) {
            console.error(err);
        }
    }, 1000)
    console.log('redirecting to: '+targetForRedirect+' in '+timeForRedirect+' second(s).');
}




/*Mediawiki editing rules enforcement*/
$( function() {

	var skipEditingCheck = '';
	if ( !$('form.mw-editform' ).length) {
		skipEditingCheck = true;
		
	} else {
		var checkEditingExcludes = ['MediaWiki:', 'Template:'];
		for ( var i = 0; i < checkEditingExcludes.length; i++ ) {
			if ( $('h1#firstHeading.firstHeading').text().indexOf( checkEditingExcludes[i]) >= 0) {
				skipEditingCheck = 'Article in namespace ' + checkEditingExcludes[i];
				break;
			}
		}
	}
skipEditingCheck = 'Awaiting explicit activation';
	if (skipEditingCheck) {
		if ( skipEditingCheck !== true ) {
			console.log( 'Skipping the editing style check: '+skipEditingCheck );
		}
		return;
	}
	
	
	var getAllPatternMatches = function(subject, pattern) {
		var results = [];
		var matches = subject.matchAll(pattern);
		var match = null;
		while( match = matches.next() ) {
			if (match.done) {
				break;
			}
			results.push(match.value);
		}
		return results;
	};
	var getSurroundingText = function(subject, startIndex, length) {
		var buffer = 40
		var start = Math.max(0, startIndex-buffer);
		var end = Math.min(subject.length, startIndex+length+buffer);
		return subject.substring(start, end);
	};

	var getEditingRulesHits = function(content) {
		var results = {};
		for (var ruleName in rules) {
			var rule = rules[ruleName];
			var newResults = [];
			if (rule['regex']) {
				var newResults = getAllPatternMatches(content, rule['regex']);
			}
			if ( newResults.length > 0 ) {
				for (var resultIndex in newResults) {
					var result = newResults[resultIndex];
					result['surroundingText'] = getSurroundingText(content, result['index'], result[0].length);
				}
				results[ruleName] = newResults;
			}
		}
		return results;
	};

	var convertResultsToDom = function(results) {
		if ( Object.values(results).length === 0 ) {
			return null;
		}
		var $output = $('<div></div>').addClass('editRulesResults');
		if ( Object.values(results).length > 0 ) {
			for (var resultName in results) {
				var rule = rules[resultName];
				var text = rule['error'] ? rule['error'] : rule['warning'];
				$results = $('<div></div>')
					.addClass('editRulesResult');
				$results.append(
						$('<span></span>')
						.addClass('editRulesResultHeader')
						.text(text)
					);
				
				var ruleResults = results[resultName];
		
				for (var resultIndex in ruleResults) {
			var result = ruleResults[resultIndex];
					var stringResult = result.surroundingText;
					$results.append( $('<div></div>')
							.addClass('editRulesResultEntry')
							.text(stringResult)
						);
				}
				$output.append($results);
			}
		}
		return $output;
	};

	var addResultsToDom = function( results ) {
		var $dom = convertResultsToDom( results );
		$('.editButtons').find('.editRulesResults').remove();
		$('.editButtons').prepend( $dom );
	};

	var checkAndReportRules = function( content ) {
		var content = $('textarea').val();
		var results = getEditingRulesHits( content );
		addResultsToDom( results );
		return Object.values(results).length;
	};
	
	var addRulesOverrideCheckboxToDom = function(  ) {
		var $overrideCheckbox = $('#mw-editpage-watch').clone();
		$overrideCheckbox.attr('id', 'mw-editpage-overridechecks');
		$overrideCheckbox.find('#wpWatchThisWidget')
			.attr('id','wpOverridCheckseWidget');
		$overrideCheckbox.find('input[type=\'checkbox\']')
			.attr('id','wpOverrideChecks')
			.attr('name','wpOverrideChecks')
			.prop( 'checked', false )
			.removeAttr('accesskey');
		$overrideCheckbox.find('label')
			.attr('for','wpOverrideChecks')
			.text('Override editing styling checks');
		
		console.log($overrideCheckbox);
		removeRulesOverrideCheckboxFromDom();
		$('#mw-editpage-watch').parent().find( '#mw-editpage-overridechecks' ).remove();
		$('#mw-editpage-watch').parent().append($overrideCheckbox);
	};
	var removeRulesOverrideCheckboxFromDom = function(  ) {
		$('#mw-editpage-watch').parent().find( '#mw-editpage-overridechecks' ).remove();
	};
	
	var submitCheckRules = function() {
		var doSubmit = true
		if ( $('#mw-editpage-overridechecks').find(':checked').length ===0 ) {
			var content = $('textarea').val();
			var results = getEditingRulesHits( content );
			addResultsToDom( results );
			doSubmit = Object.values(results).length === 0;
		}
		if (!doSubmit) {
			addRulesOverrideCheckboxToDom();
		}
		
		return doSubmit;
	};
	
	var rules = {
			'Avoid <br>': { 'regex': /(<br(\s[^>]*)*>(\s)*)+/ig, 'warning':'There is an instance of a manual <br>.'}
		};
	
		$('form.mw-editform').on('submit', function(){
			var doSubmit = submitCheckRules();
			console.log( 'Result from checking editing rules: '+doSubmit );
			return doSubmit;
		});
		
		$('form.mw-editform').find('textarea').on('change input', function(){
			removeRulesOverrideCheckboxFromDom();
		});
		
		console.log('Editing style checking enabled.');
});