User:Magnus Manske/smiles gadget.js

From Wikidata
Jump to navigation Jump to search

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
/*

 This gadget displays SMILES renderings for chemical compounds, 
 where the item contains statements for P233 and/or P2017.
 Example item: https://www.wikidata.org/wiki/Q105023200

 To add this gadget, put the following line on your common.js User subpage:

 importScript( 'User:Magnus_Manske/smiles_gadget.js' );

 NOTE: This script uses a Toolforge-hosted copy of the JS code from https://github.com/reymond-group/smilesDrawer
*/

function renderSMILES(prop) {
	$('#'+prop+' div.wikibase-statementview').each ( function ( dummy , element ) {
		let id = 'smiles_'+$(element).attr('id');
		let html = '<canvas class="smiles_canvas" id="'+id+'" style="width: 300px; height: 200px;"></canvas>'
		$(element).append(html);
		let smiles_string = $(element).find('div.wikibase-snakview-value').eq(0).text();
		let smilesDrawer = new SmilesDrawer.Drawer({width:300,height:200});
		SmilesDrawer.parse(smiles_string, function(tree) {
			smilesDrawer.draw(tree, id, "light", false);
		});
	} ) ;
}

if ( $('#P233, #P2017').length>0 ) {
	mw.loader.getScript( '//wikidata-todo.toolforge.org/smiles-drawer.min.js' )
	.then(function () {
		$('canvas.smiles_canvas').remove();
		renderSMILES ( 'P233' ) ;
		renderSMILES ( 'P2017' ) ;
	}) ;
}