User:Cobaltcigs/DiffPreviewFindLine.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function GetCharacterIndices(s, c) {
	var a = [];
	for(var i = 0; i < s.length; i++) if(s[i] === c) a.push(i);
	return a;
	}

function FindLine(num) {
	var wpTextbox1 = document.getElementById("wpTextbox1");
	var indices = GetCharacterIndices(wpTextbox1.value, '\n');
	indices.unshift(-1);
	var start = indices[num-1]+1, end = indices[num];
	var tmp = wpTextbox1.value;
	location.hash = "";
	wpTextbox1.scrollTop = 0;
	wpTextbox1.value = tmp.substring(0, end);
	wpTextbox1.scrollTop = wpTextbox1.scrollHeight;
	wpTextbox1.value = tmp;
	location.hash = "#wpTextbox1";
	wpTextbox1.selectionStart = wpTextbox1.selectionEnd = start;
	wpTextbox1.blur();
	wpTextbox1.focus();
	wpTextbox1.setSelectionRange(start, end);
	}

function DiffPreviewFindLineSetup() {
	var wikiDiff = document.getElementById("wikiDiff");
	var isShowChanges = wikiDiff && (mw.config.get('wgAction') == "submit");
	if(!isShowChanges) return;
	var trs = wikiDiff.getElementsByTagName("tr"), lineNum = 0;
	for(var i = 1; i < trs.length; i++) { 
		var tds = trs[i].getElementsByTagName("td");
		if(tds.length == 2) {
			lineNum = parseInt(tds[1].innerText.replace(/\D/g, ""));
			continue;
			}
		var last = tds[tds.length-1];
		if(/\bdiff-empty\b/.test(last.className)) continue;
		last.setAttribute("onclick", "FindLine(" + lineNum + ")");
		lineNum++;
		}
	}