Skip to content

Commit

Permalink
Style Engine: Try simple approach for consolidating styles into a sin…
Browse files Browse the repository at this point in the history
…gle style tag
  • Loading branch information
andrewserong committed Feb 22, 2022
1 parent 69c57ce commit 55e92f5
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/block-supports/layout.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ function gutenberg_render_layout_support_flag( $block_content, $block ) {
1
);

gutenberg_enqueue_block_support_styles( $style );
WP_Style_Engine_Gutenberg::get_instance()->add_style( $class_name, $style );

return $content;
}
Expand Down
69 changes: 69 additions & 0 deletions lib/class-wp-style-engine.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php
/**
* WP_Style_Engine class
*
* @package Gutenberg
*/

/**
* Singleton class representing the style engine.
*
* Consolidates rendering block styles to reduce duplication and streamline
* CSS styles generation.
*
* @since 6.0.0
*/
class WP_Style_Engine_Gutenberg {
/**
* Registered CSS styles.
*
* @since 5.5.0
* @var array
*/
private $registered_styles = array();

/**
* Container for the main instance of the class.
*
* @since 5.5.0
* @var WP_Style_Engine_Gutenberg|null
*/
private static $instance = null;

public function __construct() {
// Borrows the logic from `gutenberg_enqueue_block_support_styles`.
$action_hook_name = 'wp_footer';
if ( wp_is_block_theme() ) {
$action_hook_name = 'wp_enqueue_scripts';
}
add_action(
$action_hook_name,
array( $this, 'output_styles' )
);
}

/**
* Utility method to retrieve the main instance of the class.
*
* The instance will be created if it does not exist yet.
*
* @return WP_Style_Engine_Gutenberg The main instance.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}

return self::$instance;
}

public function add_style( $key, $value ) {
$this->registered_styles[ $key ] = $value;
}

public function output_styles() {
$style = implode( "\n", $this->registered_styles );
echo "<style>$style</style>\n";
}
}
5 changes: 5 additions & 0 deletions lib/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ function gutenberg_is_experiment_enabled( $name ) {
require __DIR__ . '/global-styles.php';
require __DIR__ . '/pwa.php';

// TODO: Before this PR merges, move this to be a part of the style engine package.
// Part of the build process should be to copy the PHP file to the correct location,
// similar to the loading behaviour in `blocks.php`.
require __DIR__ . '/class-wp-style-engine.php';

require __DIR__ . '/block-supports/elements.php';
require __DIR__ . '/block-supports/colors.php';
require __DIR__ . '/block-supports/typography.php';
Expand Down

0 comments on commit 55e92f5

Please sign in to comment.