User:Guycn2/RefineCodeReader.js

From Meta, a Wikimedia project coordination wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/*

Enhance the layout of CSS, JS, Lua and other syntax-highlighted
code when using the desktop interface on a mobile device.

Written by: [[User:Guycn2]]

*/

( async () => {
	
	'use strict';
	
	const isMobile =
		/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
		.test( navigator.userAgent );
	
	if ( !isMobile || mw.config.get( 'skin' ) === 'minerva' ) {
		return;
	}
	
	await $.when( $.ready );
	
	const $preElements = $( '.mw-highlight > pre' );
	
	if ( !$preElements.length ) {
		return;
	}
	
	await mw.loader.using( [ 'mediawiki.util', 'oojs-ui-core' ] );
	
	mw.util.addCSS( `
		.mw-highlight > pre {
			tab-size: 2;
			line-height: 1.68;
			margin-top: .43rem;
		}
		
		.linenos::before {
			font-size: 73%;
		}
	` );
	
	const cssWithLineWrap = {
		fontSize: '0.73rem',
		whiteSpace: 'pre-wrap',
		overflowX: 'hidden'
	};
	
	const cssWithoutLineWrap = {
		fontSize: '0.95rem',
		whiteSpace: 'pre',
		overflowX: 'scroll'
	};
	
	$preElements.each( ( index, element ) => {
		
		const $preElement = $( element );
		
		$preElement.css( cssWithoutLineWrap );
		
		const tog = new OO.ui.ToggleSwitchWidget();
		
		tog.$element.css( 'scale', '0.8' );
		
		tog.on( 'change', value =>
			$preElement.css( value ? cssWithLineWrap : cssWithoutLineWrap )
		);
		
		const field = new OO.ui.FieldLayout( tog, { label: 'Line wrap' } );
		
		field.$element.css( 'direction', 'ltr' );
		
		const $fieldBody = field.$element.children( '.oo-ui-fieldLayout-body' );
		
		$fieldBody.css( { 'float': 'right', alignItems: 'center' } );
		
		$fieldBody
		.children( '.oo-ui-fieldLayout-header' ).css( 'flex-shrink', '0' )
		.children( '.oo-ui-labelElement-label' ).css( {
			marginRight: '0.11rem',
			fontSize: '95%'
		} );
		
		$preElement.parent( '.mw-highlight' ).before( field.$element );
		
	} );
	
} )();