User:Samwilson/PreviewWhileEditing.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
/**
 * 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 ) {
		var info = imageInfo.query.pages[ mw.config.get( 'wgArticleId' ) ].imageinfo[ 0 ],
			para = document.createElement( 'p' ),
			br = document.createElement( 'p' ),
			img = document.createElement( 'img' ),
			contentSub = document.getElementById( 'contentSub' ),
			metadata = 'Metadata — ';
		// Go through EXIF metadata.
		if ( info.metadata === null ) {
			metadata += 'No metadata found.';
		} else {
			info.metadata.forEach( function( item ) {
				[ 'Make', 'Model', 'DateTimeOriginal', 'CreateDate' ].forEach( function ( tag ) {
					if ( item.name === tag ) {
						metadata += tag + ': ' + item.value + '; ';
					}
				} );
			});
		}

		// Construct output HTML.
		img.src = info.thumburl;
		para.className = 'preview-while-editing';
		para.append( img, metadata );
		contentSub.append( para );
	}

};

PreviewWhileEditing.main();