User:Lucas Werkmeister (WMDE)/colorIndicator.js

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.
// NOTE: this user script cannot be used yet! See https://www.wikidata.org/wiki/Special:PermanentLink/588239932#Gadget_.2F_userscript_editor_feedback_wanted

/*
 * User script to add a small indicator to “sRGB color hex triplet” statements,
 * showing the color specified in the statement.
 */

// TODO it would be nice to support qualifiers and references as well

/**
 * @type {string} the property ID of the “sRGB color hex triplet” property
 */
var RGB_PROPERTY_ID = 'P465';

/**
 * Add the indicator to the statement with the given ID.
 * @param {string} statementId the statement ID
 */
function addColorIndicator( statementId ) {
  var $statement = $( '.wikibase-statement-' + $.escapeSelector( statementId ) );

  if ( $statement.parents( '#' + $.escapeSelector( RGB_PROPERTY_ID ) ).length === 0 ) {
  	// not an “sRGB color hex triplet” statement, skip
    return;
  }

  var $mainsnak = $statement.find( '.wikibase-statementview-mainsnak .wikibase-snakview' ),
      // $value is either the inner .valueview-instaticmode element (which appears after editing a statement),
      // or, if that doesn’t exist, the outer .wikibase-snakview-value element
      $value = $mainsnak.find( '.wikibase-snakview-value' ).find( '.valueview-instaticmode' ).addBack().first(),
      // statement value (without #)
      rgb = $value.text(),
      // list of indicators on the main snak
      $indicators = $mainsnak.find( '.wikibase-snakview-indicators' ),
      // new indicator (the .wikibase-snakview-indicator class adds some default styling)
      $indicator = $( '<span>' )
        .addClass( 'wikibase-snakview-indicator gadget-colorIndicator-indicator' )
        .text( '●' ) // U+25CF BLACK CIRCLE
        .css( { color: '#' + rgb } );
  $indicators.append( $indicator );
}

// add initial indicators when the page is loaded
mw.hook( 'wikibase.entityPage.entityLoaded' ).add( function( entityData ) {
  if ( RGB_PROPERTY_ID in entityData.claims ) {
    var colorStatements = entityData.claims[ RGB_PROPERTY_ID ];
    colorStatements.forEach( function( colorStatement ) {
      addColorIndicator( colorStatement.id );
    } );
  }
} );

// re-add indicators each time a statement is saved
mw.hook( 'wikibase.statement.saved' ).add( function( entityId, statementId ) {
  addColorIndicator( statementId );
} );