Make WordPress Core

Opened 4 years ago

Last modified 22 months ago

#56251 new defect (bug)

Use dominant color in media library

Reported by: pbearne Owned by:
Priority: normal Milestone: Awaiting Review
Component: General Version:
Severity: normal Keywords: has-patch
Cc: Focuses:

Description

This is a follow-up on ticket from https://core.trac.wordpress.org/ticket/56151

Now we have Dominant color in core we should start to us it
This patch adds it to the Media library module in core

Change History (2)

This ticket was mentioned in PR #2907 on WordPress/wordpress-develop by pbearne.


4 years ago
#1

  • Keywords has-patch added

#2 @pbearne
22 months ago

Hi All

I think I have a way to do this in the plugin.

Here is the proof of concept code

Will the work?
I could do with someone better at JS to lookover replace the code.

add_action( 'admin_enqueue_scripts', function (){
	$handle = 'dominant-color-admin-styles';
	// PHPCS ignore reason: Version not used since this handle is only registered for adding an inline style.
	// phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
	wp_register_style( $handle, false );
	wp_enqueue_style( $handle );
	$custom_css = '.wp-core-ui .attachment-preview[data-dominant-color]:not(.has-transparency) { background-color: var(--dominant-color); }';
	wp_add_inline_style( $handle, $custom_css );
});

add_action( 'admin_print_footer_scripts', function (){
?>
<script>
	(function() {
		var s = jQuery( '#tmpl-attachment' )
		var n = s[0].innerText.replace( '{{ data.orientation }}"', '{{ data.orientation }} {{ data.hasTransparencyClass }}"	data-dominant-color="{{ data.dominantColor }}" data-has-transparency="{{ data.hasTransparency }}" style="--dominant-color: #{{ data.dominantColor }};"')
s.replaceWith( '<script type="text/html" id="tmpl-attachment">' + n  );
	}());
</script>
<?php

}, 1000 );

add_filter( 'wp_prepare_attachment_for_js', function( $response, $attachment, $meta ){

	$response['dominantColor'] = '';
	if ( isset( $meta['dominant_color'] ) ) {
		$response['dominantColor'] = $meta['dominant_color'];
	}
	$response['hasTransparency'] = '';
	$response['hasTransparencyClass'] = '';
	if ( isset( $meta['has_transparency'] ) ) {
		$response['hasTransparency'] = $meta['has_transparency'];
		$response['hasTransparencyClass'] = $meta['has_transparency'] ? 'has-transparency' : 'not-transparent';
	}

	return $response;
}, 10, 3 );
Note: See TracTickets for help on using tickets.