From da757b63f4f9ff46b9550c7ed540d1caf7af7112 Mon Sep 17 00:00:00 2001 From: gkaragia <53191348+gkaragia@users.noreply.github.com> Date: Tue, 19 Dec 2023 17:02:12 +0200 Subject: [PATCH] Expand the UI to inline CSS (#2682) * Enable UI to initiate CSS variables * Add argument type Co-authored-by: Fernando Jorge Mota * Add argument type Co-authored-by: Fernando Jorge Mota * Add argument type Co-authored-by: Fernando Jorge Mota * Initialize all variables Co-authored-by: Fernando Jorge Mota * Escape css values Co-authored-by: Peter Kiss * Merge styles to the array instead of overwriting --------- Co-authored-by: Fernando Jorge Mota Co-authored-by: Peter Kiss --- includes/ui/class-ui.php | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/includes/ui/class-ui.php b/includes/ui/class-ui.php index e369600a5..4e0814d8d 100644 --- a/includes/ui/class-ui.php +++ b/includes/ui/class-ui.php @@ -34,12 +34,21 @@ class UI { * * @var bool */ - private $has_ui = false; + private bool $has_ui; + + /** + * An array of css variables to be enqueued with the styles. + * + * @var array + */ + private array $css_variables; /** * Instance constructor */ private function __construct() { + $this->has_ui = false; + $this->css_variables = []; add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_styles' ] ); } @@ -53,14 +62,39 @@ public function enqueue_styles() { if ( $this->has_ui ) { wp_enqueue_style( 'wp-job-manager-ui' ); + + if ( ! empty( $this->css_variables ) ) { + wp_add_inline_style( 'wp-job-manager-ui', $this->generate_inline_css() ); + } } } /** * Request the styles to be loaded for the page. + * + * @param array $css_variables An array of CSS variables to be enqueued: => . + */ + public static function ensure_styles( array $css_variables = [] ) { + self::instance()->has_ui = true; + self::instance()->css_variables = array_merge( self::instance()->css_variables, $css_variables ); + } + + /** + * Generates CSS to be inlined with the UI styles. + * + * @return string The CSS. */ - public static function ensure_styles() { - self::instance()->has_ui = true; + private function generate_inline_css() { + + $css = ':root{'; + + foreach ( $this->css_variables as $name => $value ) { + $css .= esc_attr( $name ) . ': ' . esc_attr( $value ) . ';'; + } + + $css .= '}'; + + return $css; } }