Make WordPress Core

Opened 2 years ago

Last modified 11 days ago

#56251 new defect (bug)

Use dominant color in media library

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

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.


2 years ago
#1

  • Keywords has-patch added

#2 @pbearne
11 days 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.