Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
320 changes: 318 additions & 2 deletions lib/compat/wordpress-6.0/class-wp-webfonts.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,23 @@
* Class WP_Webfonts
*/
class WP_Webfonts {
/**
* The name of the theme mod that stores the template webfonts cache.
*
* @static
* @access private
* @var string
*/
private static $template_webfonts_cache_theme_mod = 'template_webfonts';

/**
* The name of the meta attribute that stores the post's webfonts cache.
*
* @static
* @access private
* @var string
*/
private static $webfonts_cache_meta_attribute = '_webfonts';

/**
* An array of registered webfonts.
Expand Down Expand Up @@ -59,10 +76,304 @@ public function init() {
}
add_action( $hook, array( $this, 'generate_and_enqueue_styles' ) );

add_action( 'init', array( $this, 'register_filter_for_current_template_webfonts_enqueuing' ) );
add_action( 'wp_loaded', array( $this, 'enqueue_webfonts_used_in_global_styles' ) );

add_filter( 'the_content', array( $this, 'enqueue_webfonts_used_in_content' ) );

$this->register_webfont_cache_invalidation_actions();

// Enqueue webfonts in the block editor.
add_action( 'admin_init', array( $this, 'generate_and_enqueue_editor_styles' ) );
}

/**
* Enqueue the webfonts used in the content.
*
* @param string $content The post content.
*
* @return string
*/
public function enqueue_webfonts_used_in_content( $content ) {
global $post;

$webfonts_used_in_post_cache = get_post_meta( $post->ID, self::$webfonts_cache_meta_attribute, true );

if ( ! $webfonts_used_in_post_cache ) {
$webfonts_used_in_post_cache = $this->collect_fonts_from_block_markup( $post->post_content );

if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
update_post_meta( $post->ID, self::$webfonts_cache_meta_attribute, $webfonts_used_in_post_cache );
}
}

$font_slugs = array_keys( $webfonts_used_in_post_cache );

foreach ( $font_slugs as $font_slug ) {
$this->enqueue_fonts_by_theme_json_slug( $font_slug );
}

return $content;
}

/**
* Set up the actions to invalidate webfont cache.
*/
private function register_webfont_cache_invalidation_actions() {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this function, I thought of two approaches:

  1. Hook into save_post and get the $post->post_type to determine the invalidation method (theme mod or meta attribute);
  2. The one I picked. I feel it's easier to understand and it looks to fit more the WP filter/action definitions.

$post_types_using_meta_attribute = array_diff(
get_post_types_by_support( 'editor' ),
array( 'wp_template', 'wp_template_part' )
);

foreach ( $post_types_using_meta_attribute as $post_type ) {
add_action( "save_post_$post_type", array( $this, 'invalidate_meta_attribute_webfonts_cache' ), 10, 2 );
}

/**
* Template and template parts are using a theme_mod.
*
* Because of the nature of templates and template parts,
* we cannot take for granted there a post in the database
* will exist because original templates (i.e. with no
* modifications) are read directly from disk.
*
* Using a theme_mod -- instead of an option for example -- gives
* us auto cleanup on theme switch for free, and that's exactly
* what we want!
*/
add_action( 'save_post_wp_template', array( $this, 'invalidate_template_webfonts_cache' ) );
add_action( 'save_post_wp_template_part', array( $this, 'invalidate_template_webfonts_cache' ) );
}

/**
* Invalidate meta attribute webfonts cache.
*
* @param integer $post_id The post ID.
*/
public function invalidate_meta_attribute_webfonts_cache( $post_id ) {
delete_post_meta( $post_id, self::$webfonts_cache_meta_attribute );
}

/**
* Enqueue the webfonts used in global styles by scanning the settings.
*/
public function enqueue_webfonts_used_in_global_styles() {
$global_styles_post_id = WP_Theme_JSON_Resolver_Gutenberg::get_user_global_styles_post_id();

$webfonts_used_in_global_styles = get_post_meta( $global_styles_post_id, self::$webfonts_cache_meta_attribute, true );

if ( ! $webfonts_used_in_global_styles ) {
$webfonts_used_in_global_styles = $this->collect_webfonts_used_in_global_styles();

if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
update_post_meta( $global_styles_post_id, self::$webfonts_cache_meta_attribute, $webfonts_used_in_global_styles );
}
}

$font_slugs = array_keys( $webfonts_used_in_global_styles );

foreach ( $font_slugs as $font_slug ) {
$this->enqueue_fonts_by_theme_json_slug( $font_slug );
}
}

/**
* Collect globally used webfonts.
*
* @return array
*/
private function collect_webfonts_used_in_global_styles() {
$global_styles = gutenberg_get_global_styles();
$webfonts_used_in_global_styles = array();

if ( isset( $global_styles['blocks'] ) ) {
// Register used fonts from blocks.
foreach ( $global_styles['blocks'] as $setting ) {
$font_family_slug = $this->get_font_family_from_setting( $setting );

if ( $font_family_slug ) {
$webfonts_used_in_global_styles[ $font_family_slug ] = 1;
}
}
}

if ( isset( $global_styles['elements'] ) ) {
// Register used fonts from elements.
foreach ( $global_styles['elements'] as $setting ) {
$font_family_slug = $this->get_font_family_from_setting( $setting );

if ( $font_family_slug ) {
$webfonts_used_in_global_styles[ $font_family_slug ] = 1;
}
}
}

// Get global font.
$font_family_slug = $this->get_font_family_from_setting( $global_styles );

if ( $font_family_slug ) {
$webfonts_used_in_global_styles[ $font_family_slug ] = 1;
}

return $webfonts_used_in_global_styles;
}

/**
* Get font family from global setting.
*
* @param mixed $setting The global setting.
* @return string|false
*/
private function get_font_family_from_setting( $setting ) {
if ( isset( $setting['typography'] ) && isset( $setting['typography']['fontFamily'] ) ) {
$font_family = $setting['typography']['fontFamily'];

preg_match( '/var\(--wp--(?:preset|custom)--font-family--(?P<slug>.+)\)/', $font_family, $matches );

if ( isset( $matches['slug'] ) ) {
return _wp_to_kebab_case( $matches['slug'] );
}

preg_match( '/var:(?:preset|custom)\|font-family\|(?P<slug>.+)/', $font_family, $matches );

if ( isset( $matches['slug'] ) ) {
return _wp_to_kebab_case( $matches['slug'] );
}
}

return false;
}

/**
* Invalidate template webfonts cache.
*/
public function invalidate_template_webfonts_cache() {
remove_theme_mod( self::$template_webfonts_cache_theme_mod );
}

/**
* Hook into every possible template so we can enqueue the webfonts used in the template
* that has been loaded in the front-end.
*/
public function register_filter_for_current_template_webfonts_enqueuing() {
$template_type_slugs = array_keys( get_default_block_template_types() );

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this work for custom templates?

@Addison-Stavlo Addison-Stavlo Mar 17, 2022 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it will only work for custom templates with the same slugs as those defaults, but I think would miss others that could be created by users or developers (like header-footer-only for example isnt part of the default list.)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if gutenberg_get_block_templates would work to create a slug list like this from? I think that should be retrieving all templates both from the theme file structure and the database.

@zaguiini zaguiini Mar 17, 2022 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, if I got this right, get_default_block_template_types returns a list of the "slots" where the templates are applied. If this is right, then I think we should be good to go -- we want to hook into the rendered templates and scan them for fonts as lazily as possible.

@zaguiini zaguiini Mar 17, 2022 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gutenberg_get_block_templates retrieves all templates, whether they're rendered or not, and that might be costly because "existing" doesn't mean that the template is actually being used. I think a good idea would be to be as lazy as possible and only cache the fonts for the templates are actively on the page.


foreach ( $template_type_slugs as $template_type_slug ) {
add_filter(
str_replace( '-', '', $template_type_slug ) . '_template',
array( $this, 'enqueue_webfonts_used_in_template' ),
10,
2
);
}
}

/**
* Enqueue the webfonts used in the template by scanning the blocks.
*
* @param string $template_path The current template path.
* @param string $template_slug The current template slug.
*
* @return void
*/
public function enqueue_webfonts_used_in_template( $template_path, $template_slug ) {
global $_wp_current_template_content;

$webfonts_used_in_templates = get_theme_mod( self::$template_webfonts_cache_theme_mod, array() );

if ( ! isset( $webfonts_used_in_templates[ $template_slug ] ) ) {
$webfonts_used_in_templates[ $template_slug ] = $this->collect_fonts_from_block_markup( $_wp_current_template_content );

if ( ! defined( 'WP_DEBUG' ) || ! WP_DEBUG ) {
set_theme_mod( self::$template_webfonts_cache_theme_mod, $webfonts_used_in_templates );
}
}

$font_slugs = array_keys( $webfonts_used_in_templates[ $template_slug ] );

foreach ( $font_slugs as $font_slug ) {
$this->enqueue_fonts_by_theme_json_slug( $font_slug );
}
}

/**
* When picking a font family in the editor, it is saved
* as a block attribute called `fontFamily.slug`.
*
* A font family could have several @font-face declarations,
* and we are registering each @font-face individually.
* Those declarations are put together in the theme.json file.
*
* But this class does not have any information the font slugs
* since the process of adding the fonts to the editor is done elsewhere.
*
* So, to enqueue a registered webfont that was picked in the editor,
* we must reach it by the slug first. This is what this function does.
*
* @param string $font_slug The slug of the font-family to enqueue.
*/
private function enqueue_fonts_by_theme_json_slug( $font_slug ) {
// Get settings from theme.json.
$theme_settings = WP_Theme_JSON_Resolver_Gutenberg::get_theme_data()->get_settings();

// Bail out early if there are no settings for webfonts.
if ( empty( $theme_settings['typography'] ) || empty( $theme_settings['typography']['fontFamilies'] ) ) {
return;
}

foreach ( $theme_settings['typography']['fontFamilies'] as $font_families ) {
foreach ( $font_families as $font_family ) {
if ( $font_slug !== $font_family['slug'] || ! isset( $font_family['fontFace'] ) ) {
continue;
}

foreach ( $font_family['fontFace'] as $webfont ) {
if ( ! isset( $webfont['id'] ) ) {
continue;
}

$id = $webfont['id'];

if ( isset( $this->registered_webfonts[ $id ] ) && ! isset( $this->enqueued_webfonts[ $id ] ) ) {
$this->enqueue_font( $id );
}
}
}
}
}

/**
* Collect webfonts used in block markup.
*
* @param string $block_markup The block markup.
*
* @return array
*/
private function collect_fonts_from_block_markup( $block_markup ) {
$webfonts_used_in_block_markup = array();

$template_blocks = parse_blocks( $block_markup );
$template_blocks = _flatten_blocks( $template_blocks );

foreach ( $template_blocks as $block ) {
if ( 'core/template-part' === $block['blockName'] ) {
$template_part = get_block_template( get_stylesheet() . '//' . $block['attrs']['slug'], 'wp_template_part' );
$fonts_in_template_part = $this->collect_fonts_from_block_markup( $template_part->content );

$webfonts_used_in_block_markup = array_merge(
$webfonts_used_in_block_markup,
$fonts_in_template_part
);
}

if ( isset( $block['attrs']['fontFamily'] ) ) {
$webfonts_used_in_block_markup[ $block['attrs']['fontFamily'] ] = 1;
}
}

return $webfonts_used_in_block_markup;
}

/**
* Get the list of registered fonts.
*
Expand Down Expand Up @@ -106,7 +417,9 @@ public function register_font( $id, $font ) {
return;
}

$font = $this->validate_font( $font );
$font['id'] = $id;
$font = $this->validate_font( $font );

if ( $font ) {
$this->registered_webfonts[ $id ] = $font;
}
Expand All @@ -129,7 +442,9 @@ public function enqueue_font( $id, $font = null ) {
}

if ( $font ) {
$font = $this->validate_font( $font );
$font['id'] = $id;
$font = $this->validate_font( $font );

$this->enqueued_webfonts[ $id ] = $font;

if ( isset( $this->registered_webfonts[ $id ] ) ) {
Expand Down Expand Up @@ -216,6 +531,7 @@ public function validate_font( $font ) {
'unicode-range',

// Exceptions.
'id',
'provider',
);

Expand Down
Loading