MediaWiki:Common.js: Difference between revisions

From Tygron Preview Support Wiki
Jump to navigation Jump to search
mNo edit summary
mNo edit summary
Line 101: Line 101:


/*Mediawiki editing rules enforcement*/
/*Mediawiki editing rules enforcement*/
var getAllPatternMatches = function(subject, pattern) {
$( function() {
    var results = [];
var getAllPatternMatches = function(subject, pattern) {
    var matches = subject.matchAll(pattern);console.log(matches);
var results = [];
    var match = null;
var matches = subject.matchAll(pattern);console.log(matches);
    while( match = matches.next() ) {
var match = null;
if (match.done) {
while( match = matches.next() ) {
break;
if (match.done) {
break;
}
results.push(match.value);
}
}
results.push(match.value);
return results;
    }
}
    return results;
var getSurroundingText = function(subject, startIndex, length) {
}
var buffer = 40
var getSurroundingText = function(subject, startIndex, length) {
var start = Math.max(0, startIndex-buffer);
    var buffer = 40
var end = Math.min(subject.length, startIndex+length+buffer);
    var start = Math.max(0, startIndex-buffer);
return subject.substring(start, end);
    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 rules = {'Avoid <br>': { 'regex': /(<br(\s[^>]*)*>(\s)*)+/ig, 'warning':'There is an instance of a manual <br>.'}};


var getRulesResults = 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) {
for (var resultIndex in newResults) {
var result = newResults[resultIndex];
var result = newResults[resultIndex];
result['surroundingText'] = getSurroundingText(content, result['index'], result[0].length);
result['surroundingText'] = getSurroundingText(content, result['index'], result[0].length);
}
results[ruleName] = newResults;
}
}
            results[ruleName] = newResults;
}
        }
return results;
    }
}
    return results;
}


var convertResultsToDom = function(results) {
var convertResultsToDom = function(results) {
    var $output = $('<div class=\'editResults\'></div>');
var $output = $('<div class=\'editResults\'></div>');
    if ( Object.values(results).length > 0 ) {
if ( Object.values(results).length > 0 ) {
        for (var resultName in results) {
for (var resultName in results) {
            console.log(resultName);
console.log(resultName);
            var rule = rules[resultName];
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);
$results.append('<span class=\'editResultsHeader\'></span>').text(text);
           
            var ruleResults = results[resultName];
var ruleResults = results[resultName];
   
            for (var resultIndex in ruleResults) {
for (var resultIndex in ruleResults) {
var result = ruleResults[resultIndex];
var result = ruleResults[resultIndex];
                var stringResult = result.surroundingText;
var stringResult = result.surroundingText;
                $results.append( $('<p></p>').text(stringResult) );
$results.append( $('<p></p>').text(stringResult) );
            }
}
            $output.append($results);
$output.append($results);
        }
}
    }
}
    return $output;
return $output;
}
}


var reportResults = function( results ) {
var reportResults = function( results ) {
    var $dom = convertResultsToDom( results );
var $dom = convertResultsToDom( results );
    $('.editButtons').find('.editResults').remove();
$('.editButtons').find('.editResults').remove();
    $('.editButtons').prepend( $dom );
$('.editButtons').prepend( $dom );
    console.log($dom);
console.log($dom);
}
}


var checkAndReportResults = function() {
var checkAndReportResults = function() {
    var content = $('textarea').val();
var content = $('textarea').val();
    var results = getRulesResults( content );
var results = getRulesResults( content );
    reportResults( results );
reportResults( results );
}
}


var checkEditing = true;
var checkEditing = true;
var checkEditingExcludes = ['MediaWiki:', 'Template:'];
var checkEditingExcludes = ['MediaWiki:', 'Template:'];
for ( var i = 0; i < checkEditingExcludes.length; i++ ) {
for ( var i = 0; i < checkEditingExcludes.length; i++ ) {
    if ( $('h1#firstHeading.firstHeading').text().indexOf( checkEditingExcludes[i]) >= 0) {
if ( $('h1#firstHeading.firstHeading').text().indexOf( checkEditingExcludes[i]) >= 0) {
        checkEditing = false;
checkEditing = false;
        console.log('Skipping the editing styling check because: '+checkEditingExcludes[i]);
console.log('Skipping the editing styling check because: '+checkEditingExcludes[i]);
        break;
break;
    }
}
}
}
if (checkEditing) {
if (checkEditing) {
//checkAndReportResults();
//checkAndReportResults();


}
}
});

Revision as of 14:11, 1 March 2022

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

/* 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(searchterm) {
	var searchterm = this.parentElement.getElementsByClassName('list-filterer-input')[0].value;
	var searchtarget = this.parentElement.getElementsByClassName(this.getAttribute('data-list'));
	var searchin = searchtarget.length>0?searchtarget:[this.parentElement.parentElement];
	var el = 'li';
	var e = this.parentElement.getElementsByTagName(el);
        for ( var i=0;i<searchin.length;i++) {
			var e = searchin[i].getElementsByTagName(el);
            for ( var i=0;i<e.length;i++ ) {
                if (e[i].title.includes(searchterm) || e[i].textContent.includes(searchterm) ) {
					e[i].style.removeProperty('display');
				} else {
					e[i].style.display='none';
				}
            }
		}
	};
    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'));
		
        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 = filterFunction;
		button.onclick = filterFunction;
		
        s[i].setAttribute('data-ready', 'ready');
        input.setAttribute('data-ready', 'ready');
        button.setAttribute('data-ready', 'ready');
    }
} );





/*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 getAllPatternMatches = function(subject, pattern) {
		var results = [];
		var matches = subject.matchAll(pattern);console.log(matches);
		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 rules = {'Avoid <br>': { 'regex': /(<br(\s[^>]*)*>(\s)*)+/ig, 'warning':'There is an instance of a manual <br>.'}};

	var getRulesResults = 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) {
		var $output = $('<div class=\'editResults\'></div>');
		if ( Object.values(results).length > 0 ) {
			for (var resultName in results) {
				console.log(resultName);
				var rule = rules[resultName];
				var text = rule['error'] ? rule['error'] : rule['warning'];
				$results = $('<div></div>');
				$results.append('<span class=\'editResultsHeader\'></span>').text(text);
				
				var ruleResults = results[resultName];
		
				for (var resultIndex in ruleResults) {
			var result = ruleResults[resultIndex];
					var stringResult = result.surroundingText;
					$results.append( $('<p></p>').text(stringResult) );
				}
				$output.append($results);
			}
		}
		return $output;
	}

	var reportResults = function( results ) {
		var $dom = convertResultsToDom( results );
		$('.editButtons').find('.editResults').remove();
		$('.editButtons').prepend( $dom );
		console.log($dom);
	}

	var checkAndReportResults = function() {
		var content = $('textarea').val();
		var results = getRulesResults( content );
		reportResults( results );
	}

	var checkEditing = true;
	var checkEditingExcludes = ['MediaWiki:', 'Template:'];
	for ( var i = 0; i < checkEditingExcludes.length; i++ ) {
		if ( $('h1#firstHeading.firstHeading').text().indexOf( checkEditingExcludes[i]) >= 0) {
			checkEditing = false;
			console.log('Skipping the editing styling check because: '+checkEditingExcludes[i]);
			break;
		}
	}
	if (checkEditing) {
	//checkAndReportResults();

	}
});