User:Samwilson/PreviewWhileEditing.js

/**
 * A user script to add a preview image above the edit box on File pages.
 *
 * Install with:
 * mw.loader.load( 'https://commons.wikimedia.org/w/index.php?title=User:Samwilson/PreviewWhileEditing.js&action=raw&ctype=text/javascript' );
 *
 */
PreviewWhileEditing = {

	main: function () {
		var isEditing = $.inArray( mw.config.get( 'wgAction' ), [ 'edit', 'submit' ] ) !== -1,
			isFile = mw.config.get( 'wgCanonicalNamespace' ) === 'File';
		if ( !isEditing || !isFile ) {
			// Only support preview in File NS.
			return;
		}
		new mw.Api().get( {
			action: 'query',
			prop: 'imageinfo',
			titles: mw.config.get( 'wgPageName' ),
			iiprop: 'url|metadata',
			iiurlwidth: 800
		} )
		.done( this.addImage );
	},

	addImage: function ( imageInfo ) {
		const info = imageInfo.query.pages[ mw.config.get( 'wgArticleId' ) ].imageinfo[ 0 ];

		const img = document.createElement( 'img' );
		img.src = info.thumburl;
		img.style.float = 'left';
		img.style.marginRight = '1em';

		const para = document.createElement( 'p' );
		para.className = 'preview-while-editing';

		// Go through EXIF metadata.
		( info.metadata || {} ).forEach( function( item ) {
			[ 'Make', 'Model', 'DateTimeOriginal', 'CreateDate', 'ExposureTime', 'FNumber' ].forEach( function ( tag ) {
				if ( item.name === tag ) {
					const tagEl = document.createElement( 'strong' );
					tagEl.append( tag + ':' );
					para.append( tagEl, ' ', item.value, document.createElement( 'br' ) );
				}
			} );
		} );

		const wrapper = document.createElement( 'div' );
		wrapper.append( img, para );
		wrapper.style.display = 'flex';
		wrapper.style.alignItems = 'end';

		const contentSub = document.getElementById( 'contentSub' );
		contentSub.append( wrapper );
		para.scrollIntoView();
	}

};

PreviewWhileEditing.main();