Jump to content

User:Jackmcbarn/parsoidview.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(){
	'use strict';
	var isParsoid = false, elem = $('#mw-content-text')[0], phpHTML = 'Loading HTML from PHP...', parsoidHTML = null;
	var portletLink = mw.util.addPortletLink( 'p-tb', '#', 'Enable Parsoid view', 't-parsoid-view-toggle' );
	$( portletLink ).click( function ( e ) {
		e.preventDefault();
		if(isParsoid) {
			elem.innerHTML = phpHTML;
			isParsoid = false;
			portletLink.firstChild.innerHTML = 'Enable Parsoid view';
		} else {
			if(!parsoidHTML) {
				parsoidHTML = 'Loading HTML from Parsoid...';
				mw.loader.load('mediawiki.skinning.content.parsoid');
				$.ajax({
					url: '/api/rest_v1/page/html/' + encodeURIComponent(mw.config.get('wgPageName')) + '/' + mw.config.get('wgRevisionId'),
					headers: {
						Accept: 'text/html; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/HTML/2.0.0"',
						'Api-User-Agent': 'parsoidview (https://en.wikipedia.org/wiki/User:Jackmcbarn/parsoidview.js)'
					},
					success: function(data) {
						var parsoidDom = new DOMParser().parseFromString(data, 'text/html');
						parsoidHTML = parsoidDom.body.innerHTML;
						if(isParsoid) {
							elem.innerHTML = parsoidHTML;
						}
					}
				});
				$.get('/w/index.php?action=render&oldid=' + mw.config.get('wgRevisionId'), function(data) {
					var phpDom = new DOMParser().parseFromString(data, 'text/html');
					$('#toc', phpDom).remove(); // hack: since Parsoid doesn't give us a TOC, ditch PHP's so things are the same on both
					phpHTML = phpDom.body.innerHTML;
					if(!isParsoid) {
						elem.innerHTML = phpHTML;
					}
				});
				$( portletLink ).css('position', 'fixed').css('top', '2em').css('right', 0);
			}
			elem.innerHTML = parsoidHTML;
			isParsoid = true;
			portletLink.firstChild.innerHTML = 'Disable Parsoid view';
		}
	});
});