duotone.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. /**
  3. * Duotone block support flag.
  4. *
  5. * Parts of this source were derived and modified from TinyColor,
  6. * released under the MIT license.
  7. *
  8. * https://github.com/bgrins/TinyColor
  9. *
  10. * Copyright (c), Brian Grinstead, http://briangrinstead.com
  11. *
  12. * Permission is hereby granted, free of charge, to any person obtaining
  13. * a copy of this software and associated documentation files (the
  14. * "Software"), to deal in the Software without restriction, including
  15. * without limitation the rights to use, copy, modify, merge, publish,
  16. * distribute, sublicense, and/or sell copies of the Software, and to
  17. * permit persons to whom the Software is furnished to do so, subject to
  18. * the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be
  21. * included in all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. *
  31. * @package WordPress
  32. * @since 5.8.0
  33. */
  34. /**
  35. * Takes input from [0, n] and returns it as [0, 1].
  36. *
  37. * Direct port of TinyColor's function, lightly simplified to maintain
  38. * consistency with TinyColor.
  39. *
  40. * @see https://github.com/bgrins/TinyColor
  41. *
  42. * @since 5.8.0
  43. * @access private
  44. *
  45. * @param mixed $n Number of unknown type.
  46. * @param int $max Upper value of the range to bound to.
  47. * @return float Value in the range [0, 1].
  48. */
  49. function wp_tinycolor_bound01( $n, $max ) {
  50. if ( 'string' === gettype( $n ) && false !== strpos( $n, '.' ) && 1 === (float) $n ) {
  51. $n = '100%';
  52. }
  53. $n = min( $max, max( 0, (float) $n ) );
  54. // Automatically convert percentage into number.
  55. if ( 'string' === gettype( $n ) && false !== strpos( $n, '%' ) ) {
  56. $n = (int) ( $n * $max ) / 100;
  57. }
  58. // Handle floating point rounding errors.
  59. if ( ( abs( $n - $max ) < 0.000001 ) ) {
  60. return 1.0;
  61. }
  62. // Convert into [0, 1] range if it isn't already.
  63. return ( $n % $max ) / (float) $max;
  64. }
  65. /**
  66. * Direct port of tinycolor's boundAlpha function to maintain consistency with
  67. * how tinycolor works.
  68. *
  69. * @see https://github.com/bgrins/TinyColor
  70. *
  71. * @since 5.9.0
  72. * @access private
  73. *
  74. * @param mixed $n Number of unknown type.
  75. * @return float Value in the range [0,1].
  76. */
  77. function _wp_tinycolor_bound_alpha( $n ) {
  78. if ( is_numeric( $n ) ) {
  79. $n = (float) $n;
  80. if ( $n >= 0 && $n <= 1 ) {
  81. return $n;
  82. }
  83. }
  84. return 1;
  85. }
  86. /**
  87. * Rounds and converts values of an RGB object.
  88. *
  89. * Direct port of TinyColor's function, lightly simplified to maintain
  90. * consistency with TinyColor.
  91. *
  92. * @see https://github.com/bgrins/TinyColor
  93. *
  94. * @since 5.8.0
  95. * @access private
  96. *
  97. * @param array $rgb_color RGB object.
  98. * @return array Rounded and converted RGB object.
  99. */
  100. function wp_tinycolor_rgb_to_rgb( $rgb_color ) {
  101. return array(
  102. 'r' => wp_tinycolor_bound01( $rgb_color['r'], 255 ) * 255,
  103. 'g' => wp_tinycolor_bound01( $rgb_color['g'], 255 ) * 255,
  104. 'b' => wp_tinycolor_bound01( $rgb_color['b'], 255 ) * 255,
  105. );
  106. }
  107. /**
  108. * Helper function for hsl to rgb conversion.
  109. *
  110. * Direct port of TinyColor's function, lightly simplified to maintain
  111. * consistency with TinyColor.
  112. *
  113. * @see https://github.com/bgrins/TinyColor
  114. *
  115. * @since 5.8.0
  116. * @access private
  117. *
  118. * @param float $p first component.
  119. * @param float $q second component.
  120. * @param float $t third component.
  121. * @return float R, G, or B component.
  122. */
  123. function wp_tinycolor_hue_to_rgb( $p, $q, $t ) {
  124. if ( $t < 0 ) {
  125. $t += 1;
  126. }
  127. if ( $t > 1 ) {
  128. $t -= 1;
  129. }
  130. if ( $t < 1 / 6 ) {
  131. return $p + ( $q - $p ) * 6 * $t;
  132. }
  133. if ( $t < 1 / 2 ) {
  134. return $q;
  135. }
  136. if ( $t < 2 / 3 ) {
  137. return $p + ( $q - $p ) * ( 2 / 3 - $t ) * 6;
  138. }
  139. return $p;
  140. }
  141. /**
  142. * Converts an HSL object to an RGB object with converted and rounded values.
  143. *
  144. * Direct port of TinyColor's function, lightly simplified to maintain
  145. * consistency with TinyColor.
  146. *
  147. * @see https://github.com/bgrins/TinyColor
  148. *
  149. * @since 5.8.0
  150. * @access private
  151. *
  152. * @param array $hsl_color HSL object.
  153. * @return array Rounded and converted RGB object.
  154. */
  155. function wp_tinycolor_hsl_to_rgb( $hsl_color ) {
  156. $h = wp_tinycolor_bound01( $hsl_color['h'], 360 );
  157. $s = wp_tinycolor_bound01( $hsl_color['s'], 100 );
  158. $l = wp_tinycolor_bound01( $hsl_color['l'], 100 );
  159. if ( 0 === $s ) {
  160. // Achromatic.
  161. $r = $l;
  162. $g = $l;
  163. $b = $l;
  164. } else {
  165. $q = $l < 0.5 ? $l * ( 1 + $s ) : $l + $s - $l * $s;
  166. $p = 2 * $l - $q;
  167. $r = wp_tinycolor_hue_to_rgb( $p, $q, $h + 1 / 3 );
  168. $g = wp_tinycolor_hue_to_rgb( $p, $q, $h );
  169. $b = wp_tinycolor_hue_to_rgb( $p, $q, $h - 1 / 3 );
  170. }
  171. return array(
  172. 'r' => $r * 255,
  173. 'g' => $g * 255,
  174. 'b' => $b * 255,
  175. );
  176. }
  177. /**
  178. * Parses hex, hsl, and rgb CSS strings using the same regex as TinyColor v1.4.2
  179. * used in the JavaScript. Only colors output from react-color are implemented.
  180. *
  181. * Direct port of TinyColor's function, lightly simplified to maintain
  182. * consistency with TinyColor.
  183. *
  184. * @see https://github.com/bgrins/TinyColor
  185. * @see https://github.com/casesandberg/react-color/
  186. *
  187. * @since 5.8.0
  188. * @since 5.9.0 Added alpha processing.
  189. * @access private
  190. *
  191. * @param string $color_str CSS color string.
  192. * @return array RGB object.
  193. */
  194. function wp_tinycolor_string_to_rgb( $color_str ) {
  195. $color_str = strtolower( trim( $color_str ) );
  196. $css_integer = '[-\\+]?\\d+%?';
  197. $css_number = '[-\\+]?\\d*\\.\\d+%?';
  198. $css_unit = '(?:' . $css_number . ')|(?:' . $css_integer . ')';
  199. $permissive_match3 = '[\\s|\\(]+(' . $css_unit . ')[,|\\s]+(' . $css_unit . ')[,|\\s]+(' . $css_unit . ')\\s*\\)?';
  200. $permissive_match4 = '[\\s|\\(]+(' . $css_unit . ')[,|\\s]+(' . $css_unit . ')[,|\\s]+(' . $css_unit . ')[,|\\s]+(' . $css_unit . ')\\s*\\)?';
  201. $rgb_regexp = '/^rgb' . $permissive_match3 . '$/';
  202. if ( preg_match( $rgb_regexp, $color_str, $match ) ) {
  203. $rgb = wp_tinycolor_rgb_to_rgb(
  204. array(
  205. 'r' => $match[1],
  206. 'g' => $match[2],
  207. 'b' => $match[3],
  208. )
  209. );
  210. $rgb['a'] = 1;
  211. return $rgb;
  212. }
  213. $rgba_regexp = '/^rgba' . $permissive_match4 . '$/';
  214. if ( preg_match( $rgba_regexp, $color_str, $match ) ) {
  215. $rgb = wp_tinycolor_rgb_to_rgb(
  216. array(
  217. 'r' => $match[1],
  218. 'g' => $match[2],
  219. 'b' => $match[3],
  220. )
  221. );
  222. $rgb['a'] = _wp_tinycolor_bound_alpha( $match[4] );
  223. return $rgb;
  224. }
  225. $hsl_regexp = '/^hsl' . $permissive_match3 . '$/';
  226. if ( preg_match( $hsl_regexp, $color_str, $match ) ) {
  227. $rgb = wp_tinycolor_hsl_to_rgb(
  228. array(
  229. 'h' => $match[1],
  230. 's' => $match[2],
  231. 'l' => $match[3],
  232. )
  233. );
  234. $rgb['a'] = 1;
  235. return $rgb;
  236. }
  237. $hsla_regexp = '/^hsla' . $permissive_match4 . '$/';
  238. if ( preg_match( $hsla_regexp, $color_str, $match ) ) {
  239. $rgb = wp_tinycolor_hsl_to_rgb(
  240. array(
  241. 'h' => $match[1],
  242. 's' => $match[2],
  243. 'l' => $match[3],
  244. )
  245. );
  246. $rgb['a'] = _wp_tinycolor_bound_alpha( $match[4] );
  247. return $rgb;
  248. }
  249. $hex8_regexp = '/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/';
  250. if ( preg_match( $hex8_regexp, $color_str, $match ) ) {
  251. $rgb = wp_tinycolor_rgb_to_rgb(
  252. array(
  253. 'r' => base_convert( $match[1], 16, 10 ),
  254. 'g' => base_convert( $match[2], 16, 10 ),
  255. 'b' => base_convert( $match[3], 16, 10 ),
  256. )
  257. );
  258. $rgb['a'] = _wp_tinycolor_bound_alpha(
  259. base_convert( $match[4], 16, 10 ) / 255
  260. );
  261. return $rgb;
  262. }
  263. $hex6_regexp = '/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/';
  264. if ( preg_match( $hex6_regexp, $color_str, $match ) ) {
  265. $rgb = wp_tinycolor_rgb_to_rgb(
  266. array(
  267. 'r' => base_convert( $match[1], 16, 10 ),
  268. 'g' => base_convert( $match[2], 16, 10 ),
  269. 'b' => base_convert( $match[3], 16, 10 ),
  270. )
  271. );
  272. $rgb['a'] = 1;
  273. return $rgb;
  274. }
  275. $hex4_regexp = '/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/';
  276. if ( preg_match( $hex4_regexp, $color_str, $match ) ) {
  277. $rgb = wp_tinycolor_rgb_to_rgb(
  278. array(
  279. 'r' => base_convert( $match[1] . $match[1], 16, 10 ),
  280. 'g' => base_convert( $match[2] . $match[2], 16, 10 ),
  281. 'b' => base_convert( $match[3] . $match[3], 16, 10 ),
  282. )
  283. );
  284. $rgb['a'] = _wp_tinycolor_bound_alpha(
  285. base_convert( $match[4] . $match[4], 16, 10 ) / 255
  286. );
  287. return $rgb;
  288. }
  289. $hex3_regexp = '/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/';
  290. if ( preg_match( $hex3_regexp, $color_str, $match ) ) {
  291. $rgb = wp_tinycolor_rgb_to_rgb(
  292. array(
  293. 'r' => base_convert( $match[1] . $match[1], 16, 10 ),
  294. 'g' => base_convert( $match[2] . $match[2], 16, 10 ),
  295. 'b' => base_convert( $match[3] . $match[3], 16, 10 ),
  296. )
  297. );
  298. $rgb['a'] = 1;
  299. return $rgb;
  300. }
  301. /*
  302. * The JS color picker considers the string "transparent" to be a hex value,
  303. * so we need to handle it here as a special case.
  304. */
  305. if ( 'transparent' === $color_str ) {
  306. return array(
  307. 'r' => 0,
  308. 'g' => 0,
  309. 'b' => 0,
  310. 'a' => 0,
  311. );
  312. }
  313. }
  314. /**
  315. * Returns the prefixed id for the duotone filter for use as a CSS id.
  316. *
  317. * @since 5.9.1
  318. * @access private
  319. *
  320. * @param array $preset Duotone preset value as seen in theme.json.
  321. * @return string Duotone filter CSS id.
  322. */
  323. function wp_get_duotone_filter_id( $preset ) {
  324. if ( ! isset( $preset['slug'] ) ) {
  325. return '';
  326. }
  327. return 'wp-duotone-' . $preset['slug'];
  328. }
  329. /**
  330. * Returns the CSS filter property url to reference the rendered SVG.
  331. *
  332. * @since 5.9.0
  333. * @since 6.1.0 Allow unset for preset colors.
  334. * @access private
  335. *
  336. * @param array $preset Duotone preset value as seen in theme.json.
  337. * @return string Duotone CSS filter property url value.
  338. */
  339. function wp_get_duotone_filter_property( $preset ) {
  340. if ( isset( $preset['colors'] ) && 'unset' === $preset['colors'] ) {
  341. return 'none';
  342. }
  343. $filter_id = wp_get_duotone_filter_id( $preset );
  344. return "url('#" . $filter_id . "')";
  345. }
  346. /**
  347. * Returns the duotone filter SVG string for the preset.
  348. *
  349. * @since 5.9.1
  350. * @access private
  351. *
  352. * @param array $preset Duotone preset value as seen in theme.json.
  353. * @return string Duotone SVG filter.
  354. */
  355. function wp_get_duotone_filter_svg( $preset ) {
  356. $filter_id = wp_get_duotone_filter_id( $preset );
  357. $duotone_values = array(
  358. 'r' => array(),
  359. 'g' => array(),
  360. 'b' => array(),
  361. 'a' => array(),
  362. );
  363. if ( ! isset( $preset['colors'] ) || ! is_array( $preset['colors'] ) ) {
  364. $preset['colors'] = array();
  365. }
  366. foreach ( $preset['colors'] as $color_str ) {
  367. $color = wp_tinycolor_string_to_rgb( $color_str );
  368. $duotone_values['r'][] = $color['r'] / 255;
  369. $duotone_values['g'][] = $color['g'] / 255;
  370. $duotone_values['b'][] = $color['b'] / 255;
  371. $duotone_values['a'][] = $color['a'];
  372. }
  373. ob_start();
  374. ?>
  375. <svg
  376. xmlns="http://www.w3.org/2000/svg"
  377. viewBox="0 0 0 0"
  378. width="0"
  379. height="0"
  380. focusable="false"
  381. role="none"
  382. style="visibility: hidden; position: absolute; left: -9999px; overflow: hidden;"
  383. >
  384. <defs>
  385. <filter id="<?php echo esc_attr( $filter_id ); ?>">
  386. <feColorMatrix
  387. color-interpolation-filters="sRGB"
  388. type="matrix"
  389. values="
  390. .299 .587 .114 0 0
  391. .299 .587 .114 0 0
  392. .299 .587 .114 0 0
  393. .299 .587 .114 0 0
  394. "
  395. />
  396. <feComponentTransfer color-interpolation-filters="sRGB" >
  397. <feFuncR type="table" tableValues="<?php echo esc_attr( implode( ' ', $duotone_values['r'] ) ); ?>" />
  398. <feFuncG type="table" tableValues="<?php echo esc_attr( implode( ' ', $duotone_values['g'] ) ); ?>" />
  399. <feFuncB type="table" tableValues="<?php echo esc_attr( implode( ' ', $duotone_values['b'] ) ); ?>" />
  400. <feFuncA type="table" tableValues="<?php echo esc_attr( implode( ' ', $duotone_values['a'] ) ); ?>" />
  401. </feComponentTransfer>
  402. <feComposite in2="SourceGraphic" operator="in" />
  403. </filter>
  404. </defs>
  405. </svg>
  406. <?php
  407. $svg = ob_get_clean();
  408. if ( ! defined( 'SCRIPT_DEBUG' ) || ! SCRIPT_DEBUG ) {
  409. // Clean up the whitespace.
  410. $svg = preg_replace( "/[\r\n\t ]+/", ' ', $svg );
  411. $svg = str_replace( '> <', '><', $svg );
  412. $svg = trim( $svg );
  413. }
  414. return $svg;
  415. }
  416. /**
  417. * Registers the style and colors block attributes for block types that support it.
  418. *
  419. * @since 5.8.0
  420. * @access private
  421. *
  422. * @param WP_Block_Type $block_type Block Type.
  423. */
  424. function wp_register_duotone_support( $block_type ) {
  425. $has_duotone_support = false;
  426. if ( property_exists( $block_type, 'supports' ) ) {
  427. $has_duotone_support = _wp_array_get( $block_type->supports, array( 'color', '__experimentalDuotone' ), false );
  428. }
  429. if ( $has_duotone_support ) {
  430. if ( ! $block_type->attributes ) {
  431. $block_type->attributes = array();
  432. }
  433. if ( ! array_key_exists( 'style', $block_type->attributes ) ) {
  434. $block_type->attributes['style'] = array(
  435. 'type' => 'object',
  436. );
  437. }
  438. }
  439. }
  440. /**
  441. * Render out the duotone stylesheet and SVG.
  442. *
  443. * @since 5.8.0
  444. * @since 6.1.0 Allow unset for preset colors.
  445. * @access private
  446. *
  447. * @param string $block_content Rendered block content.
  448. * @param array $block Block object.
  449. * @return string Filtered block content.
  450. */
  451. function wp_render_duotone_support( $block_content, $block ) {
  452. $block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block['blockName'] );
  453. $duotone_support = false;
  454. if ( $block_type && property_exists( $block_type, 'supports' ) ) {
  455. $duotone_support = _wp_array_get( $block_type->supports, array( 'color', '__experimentalDuotone' ), false );
  456. }
  457. $has_duotone_attribute = isset( $block['attrs']['style']['color']['duotone'] );
  458. if (
  459. ! $duotone_support ||
  460. ! $has_duotone_attribute
  461. ) {
  462. return $block_content;
  463. }
  464. $colors = $block['attrs']['style']['color']['duotone'];
  465. $filter_key = is_array( $colors ) ? implode( '-', $colors ) : $colors;
  466. $filter_preset = array(
  467. 'slug' => wp_unique_id( sanitize_key( $filter_key . '-' ) ),
  468. 'colors' => $colors,
  469. );
  470. $filter_property = wp_get_duotone_filter_property( $filter_preset );
  471. $filter_id = wp_get_duotone_filter_id( $filter_preset );
  472. $scope = '.' . $filter_id;
  473. $selectors = explode( ',', $duotone_support );
  474. $scoped = array();
  475. foreach ( $selectors as $sel ) {
  476. $scoped[] = $scope . ' ' . trim( $sel );
  477. }
  478. $selector = implode( ', ', $scoped );
  479. // !important is needed because these styles render before global styles,
  480. // and they should be overriding the duotone filters set by global styles.
  481. $filter_style = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG
  482. ? $selector . " {\n\tfilter: " . $filter_property . " !important;\n}\n"
  483. : $selector . '{filter:' . $filter_property . ' !important;}';
  484. wp_register_style( $filter_id, false, array(), true, true );
  485. wp_add_inline_style( $filter_id, $filter_style );
  486. wp_enqueue_style( $filter_id );
  487. if ( 'unset' !== $colors ) {
  488. $filter_svg = wp_get_duotone_filter_svg( $filter_preset );
  489. add_action(
  490. 'wp_footer',
  491. static function () use ( $filter_svg, $selector ) {
  492. echo $filter_svg;
  493. /*
  494. * Safari renders elements incorrectly on first paint when the
  495. * SVG filter comes after the content that it is filtering, so
  496. * we force a repaint with a WebKit hack which solves the issue.
  497. */
  498. global $is_safari;
  499. if ( $is_safari ) {
  500. /*
  501. * Simply accessing el.offsetHeight flushes layout and style
  502. * changes in WebKit without having to wait for setTimeout.
  503. */
  504. printf(
  505. '<script>( function() { var el = document.querySelector( %s ); var display = el.style.display; el.style.display = "none"; el.offsetHeight; el.style.display = display; } )();</script>',
  506. wp_json_encode( $selector )
  507. );
  508. }
  509. }
  510. );
  511. }
  512. // Like the layout hook, this assumes the hook only applies to blocks with a single wrapper.
  513. return preg_replace(
  514. '/' . preg_quote( 'class="', '/' ) . '/',
  515. 'class="' . $filter_id . ' ',
  516. $block_content,
  517. 1
  518. );
  519. }
  520. // Register the block support.
  521. WP_Block_Supports::get_instance()->register(
  522. 'duotone',
  523. array(
  524. 'register_attribute' => 'wp_register_duotone_support',
  525. )
  526. );
  527. add_filter( 'render_block', 'wp_render_duotone_support', 10, 2 );