wp-customize-colors-preview.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. if ( userColorPalette && userColorSectionKey ) {
  2. // For each of the palette items add a listener
  3. userColorPalette.forEach( ( paletteItem ) => {
  4. const settingName = userColorSectionKey + paletteItem.slug;
  5. wp.customize( settingName, ( value ) => {
  6. value.bind( ( newValue ) => {
  7. paletteItem.color = newValue;
  8. blockBaseUpdateColorsPreview( userColorPalette );
  9. } );
  10. } );
  11. } );
  12. }
  13. function blockBaseUpdateColorsPreview( palette ) {
  14. // build the CSS variables to inject
  15. let innerHTML = ':root,body{';
  16. palette.forEach( ( paletteItem ) => {
  17. innerHTML += `--wp--preset--color--${ paletteItem.slug }:${ paletteItem.color };`;
  18. } );
  19. innerHTML += ';}';
  20. // inject them into the body
  21. const styleElement = document.getElementById(
  22. 'global-styles-colors-customizations-inline-css'
  23. );
  24. styleElement.innerHTML = innerHTML;
  25. if ( window.userColorDuotone ) {
  26. const colors = palette.map( ( paletteItem ) => paletteItem.color );
  27. //we are inverting the order when we have a darker background so that duotone looks good.
  28. colors.sort( ( first, second ) => {
  29. if (
  30. colord( first ).brightness() > colord( second ).brightness()
  31. ) {
  32. return 1;
  33. }
  34. return -1;
  35. } );
  36. const colorValues = getValuesFromColors( colors );
  37. updateDuotoneFilter( '#wp-duotone-default-filter', colorValues );
  38. updateDuotoneFilter( '#wp-duotone-custom-filter', colorValues );
  39. }
  40. }
  41. function updateDuotoneFilter( filterID, colors ) {
  42. if ( document.querySelector( filterID ) ) {
  43. document
  44. .querySelector( filterID + ' feFuncR' )
  45. .setAttribute( 'tableValues', colors.r.join( ' ' ) );
  46. document
  47. .querySelector( filterID + ' feFuncG' )
  48. .setAttribute( 'tableValues', colors.g.join( ' ' ) );
  49. document
  50. .querySelector( filterID + ' feFuncB' )
  51. .setAttribute( 'tableValues', colors.b.join( ' ' ) );
  52. }
  53. }
  54. // This function is from Gutenberg.
  55. function getValuesFromColors( colors = [] ) {
  56. const values = { r: [], g: [], b: [] };
  57. colors.forEach( ( color ) => {
  58. const rgbColor = colord( color ).toRgb();
  59. values.r.push( rgbColor.r / 255 );
  60. values.g.push( rgbColor.g / 255 );
  61. values.b.push( rgbColor.b / 255 );
  62. } );
  63. return values;
  64. }