Skip to content

Commit

Permalink
Expand the UI to inline CSS (#2682)
Browse files Browse the repository at this point in the history
* Enable UI to initiate CSS variables

* Add argument type

Co-authored-by: Fernando Jorge Mota <[email protected]>

* Add argument type

Co-authored-by: Fernando Jorge Mota <[email protected]>

* Add argument type

Co-authored-by: Fernando Jorge Mota <[email protected]>

* Initialize all variables

Co-authored-by: Fernando Jorge Mota <[email protected]>

* Escape css values

Co-authored-by: Peter Kiss <[email protected]>

* Merge styles to the array instead of overwriting

---------

Co-authored-by: Fernando Jorge Mota <[email protected]>
Co-authored-by: Peter Kiss <[email protected]>
  • Loading branch information
3 people authored Dec 19, 2023
1 parent e27c1e5 commit da757b6
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions includes/ui/class-ui.php
Original file line number Diff line number Diff line change
Expand Up @@ -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' ] );
}

Expand All @@ -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: <variable_name> => <value>.
*/
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;
}
}

Expand Down

0 comments on commit da757b6

Please sign in to comment.