User:SD0001/inline-tags.js

if (mw.config.get('wgPageName') !== 'User:SD0001/sandbox') { return; } $.ajax('https://en.wikipedia.org/api/rest_v1/page/html/' + encodeURIComponent(mw.config.get('wgPageName'))).then(function(html, status, response) {	$('.mw-parser-output').html(html).css('background', '#e7eeef').click(function(evt) { //console.log(evt.target); });	return response.getResponseHeader('etag'); }).then(function(etag){	$.getJSON('https://en.wikipedia.org/api/rest_v1/page/data-parsoid/' + encodeURIComponent(mw.config.get('wgPageName')) + '/' + etag.slice(1,-1) ).then(function(json) { psdData = json; }); }); $(mw.util.addPortletLink('p-tb', '#', 'inline-tag', 'cn', 'Add inline tag')).click(async function(e) {	e.preventDefault;	selection = window.getSelection;	console.log(selection);	startNode = selection.anchorNode;	endNode = selection.focusNode;	if (selection.anchorNode.compareDocumentPosition(selection.focusNode) === Node.DOCUMENT_POSITION_PRECEDING) {		startNode = selection.focusNode;		endNode = selection.anchorNode;		console.log('swapped');	}	var commonNode;	if (startNode === endNode) {		commonNode = startNode;	} else {		;	}	// find closest ancestor with id beginning with mw*	var element = startNode.parentElement;	while (element.id.indexOf('mw') !== 0) {		element = element.parentElement;		if (!element) {			console.error('Could\'t complete traversal');		}	}	var dsr = psdData.ids[element.id].dsr;	var textToSearchIn = text.slice(dsr[0], dsr[1]);	var selText = selection.toString; var idx = textToSearchIn.indexOf(selText); if (idx === -1) { console.error('Couldn\'t find text at expected place'); }	var sectionNumber = $(endNode).parentsUntil('section').parent.attr('data-mw-section-id'); console.log(sectionNumber); var sectionText = await getSectionWikitext(sectionNumber); var selText = selection.toString; console.log(selText); new Morebits.wiki.page(mw.config.get('wgPageName')).load(function(e) {		var idx = e.getPageText.indexOf(selText);		if (idx === -1) {			console.warn('Couldn\'t find the given text, maybe it is (entirely or partially) within a template');			return;       } else {			console.log('idx', idx);		}		console.log(e.getPageText.replace(selText, selText + ''));    }); }); function getSectionWikitext(num) {	return new Morebits.wiki.api('parse section', { "action": "query", "prop": "revisions", "titles": "User:SD0001/sandbox", "rvprop": "content", "rvlimit": "1", "rvsection": num.toString }).post.then(function(r) { return $(r.response).find('rev').text; }); } function wikitextToText(wikitext) {	return wikitext		.replace(/\[\[:?(?:[^\|\]]+?\|)?([^\]\|]+?)\]\]/g, "$1") // links		.replace(/('''?)(.+?)\1/g, "$2") // bold/italics		.replace(/ (.+?)<\/s>/g, "$1")		.replace(/(.*?)<\/span>/g, "$1"); }