ince 5.0.0
*
* @param string $parser_class Name of block parser class.
*/
$parser_class = apply_filters( 'block_parser_class', 'WP_Block_Parser' );
$parser = new $parser_class();
return $parser->parse( $content );
}
/**
* Parses dynamic blocks out of `post_content` and re-renders them.
*
* @since 5.0.0
*
* @param string $content Post content.
* @return string Updated post content.
*/
function do_blocks( $content ) {
$blocks = parse_blocks( $content );
$output = '';
foreach ( $blocks as $block ) {
$output .= render_block( $block );
}
// If there are blocks in this content, we shouldn't run wpautop() on it later.
$priority = has_filter( 'the_content', 'wpautop' );
if ( false !== $priority && doing_filter( 'the_content' ) && has_blocks( $content ) ) {
remove_filter( 'the_content', 'wpautop', $priority );
add_filter( 'the_content', '_restore_wpautop_hook', $priority + 1 );
}
return $output;
}
/**
* If do_blocks() needs to remove wpautop() from the `the_content` filter, this re-adds it afterwards,
* for subsequent `the_content` usage.
*
* @since 5.0.0
* @access private
*
* @param string $content The post content running through this filter.
* @return string The unmodified content.
*/
function _restore_wpautop_hook( $content ) {
$current_priority = has_filter( 'the_content', '_restore_wpautop_hook' );
add_filter( 'the_content', 'wpautop', $current_priority - 1 );
remove_filter( 'the_content', '_restore_wpautop_hook', $current_priority );
return $content;
}
/**
* Returns the current version of the block format that the content string is using.
*
* If the string doesn't contain blocks, it returns 0.
*
* @since 5.0.0
*
* @param string $content Content to test.
* @return int The block format version is 1 if the content contains one or more blocks, 0 otherwise.
*/
function block_version( $content ) {
return has_blocks( $content ) ? 1 : 0;
}
/**
* Registers a new block style.
*
* @since 5.3.0
* @since 6.6.0 Added support for registering styles for multiple block types.
*
* @link https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/
*
* @param string|string[] $block_name Block type name including namespace or array of namespaced block type names.
* @param array $style_properties Array containing the properties of the style name, label,
* style_handle (name of the stylesheet to be enqueued),
* inline_style (string containing the CSS to be added),
* style_data (theme.json-like array to generate CSS from).
* See WP_Block_Styles_Registry::register().
* @return bool True if the block style was registered with success and false otherwise.
*/
function register_block_style( $block_name, $style_properties ) {
return WP_Block_Styles_Registry::get_instance()->register( $block_name, $style_properties );
}
/**
* Unregisters a block style.
*
* @since 5.3.0
*
* @param string $block_name Block type name including namespace.
* @param string $block_style_name Block style name.
* @return bool True if the block style was unregistered with success and false otherwise.
*/
function unregister_block_style( $block_name, $block_style_name ) {
return WP_Block_Styles_Registry::get_instance()->unregister( $block_name, $block_style_name );
}
/**
* Checks whether the current block type supports the feature requested.
*
* @since 5.8.0
* @since 6.4.0 The `$feature` parameter now supports a string.
*
* @param WP_Block_Type $block_type Block type to check for support.
* @param string|array $feature Feature slug, or path to a specific feature to check support for.
* @param mixed $default_value Optional. Fallback value for feature support. Default false.
* @return bool Whether the feature is supported.
*/
function block_has_support( $block_type, $feature, $default_value = false ) {
$block_support = $default_value;
if ( $block_type instanceof WP_Block_Type ) {
if ( is_array( $feature ) && count( $feature ) === 1 ) {
$feature = $feature[0];
}
if ( is_array( $feature ) ) {
$block_support = _wp_array_get( $block_type->supports, $feature, $default_value );
} elseif ( isset( $block_type->supports[ $feature ] ) ) {
$block_support = $block_type->supports[ $feature ];
}
}
return true === $block_support || is_array( $block_support );
}
/**
* Converts typography keys declared under `supports.*` to `supports.typography.*`.
*
* Displays a `_doing_it_wrong()` notice when a block using the older format is detected.
*
* @since 5.8.0
*
* @param array $metadata Metadata for registering a block type.
* @return array Filtered metadata for registering a block type.
*/
function wp_migrate_old_typography_shape( $metadata ) {
if ( ! isset( $metadata['supports'] ) ) {
return $metadata;
}
$typography_keys = array(
'__experimentalFontFamily',
'__experimentalFontStyle',
'__experimentalFontWeight',
'__experimentalLetterSpacing',
'__experimentalTextDecoration',
'__experimentalTextTransform',
'fontSize',
'lineHeight',
);
foreach ( $typography_keys as $typography_key ) {
$support_for_key = isset( $metadata['supports'][ $typography_key ] ) ? $metadata['supports'][ $typography_key ] : null;
if ( null !== $support_for_key ) {
_doing_it_wrong(
'register_block_type_from_metadata()',
sprintf(
/* translators: 1: Block type, 2: Typography supports key, e.g: fontSize, lineHeight, etc. 3: block.json, 4: Old metadata key, 5: New metadata key. */
__( 'Block "%1$s" is declaring %2$s support in %3$s file under %4$s. %2$s support is now declared under %5$s.' ),
$metadata['name'],
"$typography_key
",
'block.json
',
"supports.$typography_key
",
"supports.typography.$typography_key
"
),
'5.8.0'
);
_wp_array_set( $metadata['supports'], array( 'typography', $typography_key ), $support_for_key );
unset( $metadata['supports'][ $typography_key ] );
}
}
return $metadata;
}
/**
* Helper function that constructs a WP_Query args array from
* a `Query` block properties.
*
* It's used in Query Loop, Query Pagination Numbers and Query Pagination Next blocks.
*
* @since 5.8.0
* @since 6.1.0 Added `query_loop_block_query_vars` filter and `parents` support in query.
*
* @param WP_Block $block Block instance.
* @param int $page Current query's page.
*
* @return array Returns the constructed WP_Query arguments.
*/
function build_query_vars_from_query_block( $block, $page ) {
$query = array(
'post_type' => 'post',
'order' => 'DESC',
'orderby' => 'date',
'post__not_in' => array(),
);
if ( isset( $block->context['query'] ) ) {
if ( ! empty( $block->context['query']['postType'] ) ) {
$post_type_param = $block->context['query']['postType'];
if ( is_post_type_viewable( $post_type_param ) ) {
$query['post_type'] = $post_type_param;
}
}
if ( isset( $block->context['query']['sticky'] ) && ! empty( $block->context['query']['sticky'] ) ) {
$sticky = get_option( 'sticky_posts' );
if ( 'only' === $block->context['query']['sticky'] ) {
/*
* Passing an empty array to post__in will return have_posts() as true (and all posts will be returned).
* Logic should be used before hand to determine if WP_Query should be used in the event that the array
* being passed to post__in is empty.
*
* @see https://core.trac.wordpress.org/ticket/28099
*/
$query['post__in'] = ! empty( $sticky ) ? $sticky : array( 0 );
$query['ignore_sticky_posts'] = 1;
} else {
$query['post__not_in'] = array_merge( $query['post__not_in'], $sticky );
}
}
if ( ! empty( $block->context['query']['exclude'] ) ) {
$excluded_post_ids = array_map( 'intval', $block->context['query']['exclude'] );
$excluded_post_ids = array_filter( $excluded_post_ids );
$query['post__not_in'] = array_merge( $query['post__not_in'], $excluded_post_ids );
}
if (
isset( $block->context['query']['perPage'] ) &&
is_numeric( $block->context['query']['perPage'] )
) {
$per_page = absint( $block->context['query']['perPage'] );
$offset = 0;
if (
isset( $block->context['query']['offset'] ) &&
is_numeric( $block->context['query']['offset'] )
) {
$offset = absint( $block->context['query']['offset'] );
}
$query['offset'] = ( $per_page * ( $page - 1 ) ) + $offset;
$query['posts_per_page'] = $per_page;
}
// Migrate `categoryIds` and `tagIds` to `tax_query` for backwards compatibility.
if ( ! empty( $block->context['query']['categoryIds'] ) || ! empty( $block->context['query']['tagIds'] ) ) {
$tax_query = array();
if ( ! empty( $block->context['query']['categoryIds'] ) ) {
$tax_query[] = array(
'taxonomy' => 'category',
'terms' => array_filter( array_map( 'intval', $block->context['query']['categoryIds'] ) ),
'include_children' => false,
);
}
if ( ! empty( $block->context['query']['tagIds'] ) ) {
$tax_query[] = array(
'taxonomy' => 'post_tag',
'terms' => array_filter( array_map( 'intval', $block->context['query']['tagIds'] ) ),
'include_children' => false,
);
}
$query['tax_query'] = $tax_query;
}
if ( ! empty( $block->context['query']['taxQuery'] ) ) {
$query['tax_query'] = array();
foreach ( $block->context['query']['taxQuery'] as $taxonomy => $terms ) {
if ( is_taxonomy_viewable( $taxonomy ) && ! empty( $terms ) ) {
$query['tax_query'][] = array(
'taxonomy' => $taxonomy,
'terms' => array_filter( array_map( 'intval', $terms ) ),
'include_children' => false,
);
}
}
}
if (
isset( $block->context['query']['order'] ) &&
in_array( strtoupper( $block->context['query']['order'] ), array( 'ASC', 'DESC' ), true )
) {
$query['order'] = strtoupper( $block->context['query']['order'] );
}
if ( isset( $block->context['query']['orderBy'] ) ) {
$query['orderby'] = $block->context['query']['orderBy'];
}
if (
isset( $block->context['query']['author'] )
) {
if ( is_array( $block->context['query']['author'] ) ) {
$query['author__in'] = array_filter( array_map( 'intval', $block->context['query']['author'] ) );
} elseif ( is_string( $block->context['query']['author'] ) ) {
$query['author__in'] = array_filter( array_map( 'intval', explode( ',', $block->context['query']['author'] ) ) );
} elseif ( is_int( $block->context['query']['author'] ) && $block->context['query']['author'] > 0 ) {
$query['author'] = $block->context['query']['author'];
}
}
if ( ! empty( $block->context['query']['search'] ) ) {
$query['s'] = $block->context['query']['search'];
}
if ( ! empty( $block->context['query']['parents'] ) && is_post_type_hierarchical( $query['post_type'] ) ) {
$query['post_parent__in'] = array_filter( array_map( 'intval', $block->context['query']['parents'] ) );
}
}
/**
* Filters the arguments which will be passed to `WP_Query` for the Query Loop Block.
*
* Anything to this filter should be compatible with the `WP_Query` API to form
* the query context which will be passed down to the Query Loop Block's children.
* This can help, for example, to include additional settings or meta queries not
* directly supported by the core Query Loop Block, and extend its capabilities.
*
* Please note that this will only influence the query that will be rendered on the
* front-end. The editor preview is not affected by this filter. Also, worth noting
* that the editor preview uses the REST API, so, ideally, one should aim to provide
* attributes which are also compatible with the REST API, in order to be able to
* implement identical queries on both sides.
*
* @since 6.1.0
*
* @param array $query Array containing parameters for `WP_Query` as parsed by the block context.
* @param WP_Block $block Block instance.
* @param int $page Current query's page.
*/
return apply_filters( 'query_loop_block_query_vars', $query, $block, $page );
}
/**
* Helper function that returns the proper pagination arrow HTML for
* `QueryPaginationNext` and `QueryPaginationPrevious` blocks based
* on the provided `paginationArrow` from `QueryPagination` context.
*
* It's used in QueryPaginationNext and QueryPaginationPrevious blocks.
*
* @since 5.9.0
*
* @param WP_Block $block Block instance.
* @param bool $is_next Flag for handling `next/previous` blocks.
* @return string|null The pagination arrow HTML or null if there is none.
*/
function get_query_pagination_arrow( $block, $is_next ) {
$arrow_map = array(
'none' => '',
'arrow' => array(
'next' => '→',
'previous' => '←',
),
'chevron' => array(
'next' => '»',
'previous' => '«',
),
);
if ( ! empty( $block->context['paginationArrow'] ) && array_key_exists( $block->context['paginationArrow'], $arrow_map ) && ! empty( $arrow_map[ $block->context['paginationArrow'] ] ) ) {
$pagination_type = $is_next ? 'next' : 'previous';
$arrow_attribute = $block->context['paginationArrow'];
$arrow = $arrow_map[ $block->context['paginationArrow'] ][ $pagination_type ];
$arrow_classes = "wp-block-query-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
return "$arrow";
}
return null;
}
/**
* Helper function that constructs a comment query vars array from the passed
* block properties.
*
* It's used with the Comment Query Loop inner blocks.
*
* @since 6.0.0
*
* @param WP_Block $block Block instance.
* @return array Returns the comment query parameters to use with the
* WP_Comment_Query constructor.
*/
function build_comment_query_vars_from_block( $block ) {
$comment_args = array(
'orderby' => 'comment_date_gmt',
'order' => 'ASC',
'status' => 'approve',
'no_found_rows' => false,
);
if ( is_user_logged_in() ) {
$comment_args['include_unapproved'] = array( get_current_user_id() );
} else {
$unapproved_email = wp_get_unapproved_comment_author_email();
if ( $unapproved_email ) {
$comment_args['include_unapproved'] = array( $unapproved_email );
}
}
if ( ! empty( $block->context['postId'] ) ) {
$comment_args['post_id'] = (int) $block->context['postId'];
}
if ( get_option( 'thread_comments' ) ) {
$comment_args['hierarchical'] = 'threaded';
} else {
$comment_args['hierarchical'] = false;
}
if ( get_option( 'page_comments' ) === '1' || get_option( 'page_comments' ) === true ) {
$per_page = get_option( 'comments_per_page' );
$default_page = get_option( 'default_comments_page' );
if ( $per_page > 0 ) {
$comment_args['number'] = $per_page;
$page = (int) get_query_var( 'cpage' );
if ( $page ) {
$comment_args['paged'] = $page;
} elseif ( 'oldest' === $default_page ) {
$comment_args['paged'] = 1;
} elseif ( 'newest' === $default_page ) {
$max_num_pages = (int) ( new WP_Comment_Query( $comment_args ) )->max_num_pages;
if ( 0 !== $max_num_pages ) {
$comment_args['paged'] = $max_num_pages;
}
}
// Set the `cpage` query var to ensure the previous and next pagination links are correct
// when inheriting the Discussion Settings.
if ( 0 === $page && isset( $comment_args['paged'] ) && $comment_args['paged'] > 0 ) {
set_query_var( 'cpage', $comment_args['paged'] );
}
}
}
return $comment_args;
}
/**
* Helper function that returns the proper pagination arrow HTML for
* `CommentsPaginationNext` and `CommentsPaginationPrevious` blocks based on the
* provided `paginationArrow` from `CommentsPagination` context.
*
* It's used in CommentsPaginationNext and CommentsPaginationPrevious blocks.
*
* @since 6.0.0
*
* @param WP_Block $block Block instance.
* @param string $pagination_type Optional. Type of the arrow we will be rendering.
* Accepts 'next' or 'previous'. Default 'next'.
* @return string|null The pagination arrow HTML or null if there is none.
*/
function get_comments_pagination_arrow( $block, $pagination_type = 'next' ) {
$arrow_map = array(
'none' => '',
'arrow' => array(
'next' => '→',
'previous' => '←',
),
'chevron' => array(
'next' => '»',
'previous' => '«',
),
);
if ( ! empty( $block->context['comments/paginationArrow'] ) && ! empty( $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ] ) ) {
$arrow_attribute = $block->context['comments/paginationArrow'];
$arrow = $arrow_map[ $block->context['comments/paginationArrow'] ][ $pagination_type ];
$arrow_classes = "wp-block-comments-pagination-$pagination_type-arrow is-arrow-$arrow_attribute";
return "$arrow";
}
return null;
}
/**
* Strips all HTML from the content of footnotes, and sanitizes the ID.
*
* This function expects slashed data on the footnotes content.
*
* @access private
* @since 6.3.2
*
* @param string $footnotes JSON-encoded string of an array containing the content and ID of each footnote.
* @return string Filtered content without any HTML on the footnote content and with the sanitized ID.
*/
function _wp_filter_post_meta_footnotes( $footnotes ) {
$footnotes_decoded = json_decode( $footnotes, true );
if ( ! is_array( $footnotes_decoded ) ) {
return '';
}
$footnotes_sanitized = array();
foreach ( $footnotes_decoded as $footnote ) {
if ( ! empty( $footnote['content'] ) && ! empty( $footnote['id'] ) ) {
$footnotes_sanitized[] = array(
'id' => sanitize_key( $footnote['id'] ),
'content' => wp_unslash( wp_filter_post_kses( wp_slash( $footnote['content'] ) ) ),
);
}
}
return wp_json_encode( $footnotes_sanitized );
}
/**
* Adds the filters for footnotes meta field.
*
* @access private
* @since 6.3.2
*/
function _wp_footnotes_kses_init_filters() {
add_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' );
}
/**
* Removes the filters for footnotes meta field.
*
* @access private
* @since 6.3.2
*/
function _wp_footnotes_remove_filters() {
remove_filter( 'sanitize_post_meta_footnotes', '_wp_filter_post_meta_footnotes' );
}
/**
* Registers the filter of footnotes meta field if the user does not have `unfiltered_html` capability.
*
* @access private
* @since 6.3.2
*/
function _wp_footnotes_kses_init() {
_wp_footnotes_remove_filters();
if ( ! current_user_can( 'unfiltered_html' ) ) {
_wp_footnotes_kses_init_filters();
}
}
/**
* Initializes the filters for footnotes meta field when imported data should be filtered.
*
* This filter is the last one being executed on {@see 'force_filtered_html_on_import'}.
* If the input of the filter is true, it means we are in an import situation and should
* enable kses, independently of the user capabilities. So in that case we call
* _wp_footnotes_kses_init_filters().
*
* @access private
* @since 6.3.2
*
* @param string $arg Input argument of the filter.
* @return string Input argument of the filter.
*/
function _wp_footnotes_force_filtered_html_on_import_filter( $arg ) {
// If `force_filtered_html_on_import` is true, we need to init the global styles kses filters.
if ( $arg ) {
_wp_footnotes_kses_init_filters();
}
return $arg;
}
array_splice( $this->context_stack, $context_stack_size );
}
/*
* It returns null if the HTML is unbalanced because unbalanced HTML is
* not safe to process. In that case, the Interactivity API runtime will
* update the HTML on the client side during the hydration. It will also
* display a notice to the developer to inform them about the issue.
*/
if ( $unbalanced || 0 < count( $tag_stack ) ) {
$tag_errored = 0 < count( $tag_stack ) ? end( $tag_stack )[0] : $tag_name;
/* translators: %1s: Namespace processed, %2s: The tag that caused the error; could be any HTML tag. */
$message = sprintf( __( 'Interactivity directives failed to process in "%1$s" due to a missing "%2$s" end tag.' ), end( $this->namespace_stack ), $tag_errored );
_doing_it_wrong( __METHOD__, $message, '6.6.0' );
return null;
}
return $p->get_updated_html();
}
/**
* Evaluates the reference path passed to a directive based on the current
* store namespace, state and context.
*
* @since 6.5.0
* @since 6.6.0 The function now adds a warning when the namespace is null, falsy, or the directive value is empty.
* @since 6.6.0 Removed `default_namespace` and `context` arguments.
*
* @param string|true $directive_value The directive attribute value string or `true` when it's a boolean attribute.
* @return mixed|null The result of the evaluation. Null if the reference path doesn't exist or the namespace is falsy.
*/
private function evaluate( $directive_value ) {
$default_namespace = end( $this->namespace_stack );
$context = end( $this->context_stack );
list( $ns, $path ) = $this->extract_directive_value( $directive_value, $default_namespace );
if ( ! $ns || ! $path ) {
/* translators: %s: The directive value referenced. */
$message = sprintf( __( 'Namespace or reference path cannot be empty. Directive value referenced: %s' ), $directive_value );
_doing_it_wrong( __METHOD__, $message, '6.6.0' );
return null;
}
$store = array(
'state' => $this->state_data[ $ns ] ?? array(),
'context' => $context[ $ns ] ?? array(),
);
// Checks if the reference path is preceded by a negation operator (!).
$should_negate_value = '!' === $path[0];
$path = $should_negate_value ? substr( $path, 1 ) : $path;
// Extracts the value from the store using the reference path.
$path_segments = explode( '.', $path );
$current = $store;
foreach ( $path_segments as $path_segment ) {
if ( ( is_array( $current ) || $current instanceof ArrayAccess ) && isset( $current[ $path_segment ] ) ) {
$current = $current[ $path_segment ];
} elseif ( is_object( $current ) && isset( $current->$path_segment ) ) {
$current = $current->$path_segment;
} else {
return null;
}
}
if ( $current instanceof Closure ) {
/*
* This state getter's namespace is added to the stack so that
* `state()` or `get_config()` read that namespace when called
* without specifying one.
*/
array_push( $this->namespace_stack, $ns );
try {
$current = $current();
} catch ( Throwable $e ) {
_doing_it_wrong(
__METHOD__,
sprintf(
/* translators: 1: Path pointing to an Interactivity API state property, 2: Namespace for an Interactivity API store. */
__( 'Uncaught error executing a derived state callback with path "%1$s" and namespace "%2$s".' ),
$path,
$ns
),
'6.6.0'
);
return null;
} finally {
// Remove the property's namespace from the stack.
array_pop( $this->namespace_stack );
}
}
// Returns the opposite if it contains a negation operator (!).
return $should_negate_value ? ! $current : $current;
}
/**
* Extracts the directive attribute name to separate and return the directive
* prefix and an optional suffix.
*
* The suffix is the string after the first double hyphen and the prefix is
* everything that comes before the suffix.
*
* Example:
*
* extract_prefix_and_suffix( 'data-wp-interactive' ) => array( 'data-wp-interactive', null )
* extract_prefix_and_suffix( 'data-wp-bind--src' ) => array( 'data-wp-bind', 'src' )
* extract_prefix_and_suffix( 'data-wp-foo--and--bar' ) => array( 'data-wp-foo', 'and--bar' )
*
* @since 6.5.0
*
* @param string $directive_name The directive attribute name.
* @return array An array containing the directive prefix and optional suffix.
*/
private function extract_prefix_and_suffix( string $directive_name ): array {
return explode( '--', $directive_name, 2 );
}
/**
* Parses and extracts the namespace and reference path from the given
* directive attribute value.
*
* If the value doesn't contain an explicit namespace, it returns the
* default one. If the value contains a JSON object instead of a reference
* path, the function tries to parse it and return the resulting array. If
* the value contains strings that represent booleans ("true" and "false"),
* numbers ("1" and "1.2") or "null", the function also transform them to
* regular booleans, numbers and `null`.
*
* Example:
*
* extract_directive_value( 'actions.foo', 'myPlugin' ) => array( 'myPlugin', 'actions.foo' )
* extract_directive_value( 'otherPlugin::actions.foo', 'myPlugin' ) => array( 'otherPlugin', 'actions.foo' )
* extract_directive_value( '{ "isOpen": false }', 'myPlugin' ) => array( 'myPlugin', array( 'isOpen' => false ) )
* extract_directive_value( 'otherPlugin::{ "isOpen": false }', 'myPlugin' ) => array( 'otherPlugin', array( 'isOpen' => false ) )
*
* @since 6.5.0
*
* @param string|true $directive_value The directive attribute value. It can be `true` when it's a boolean
* attribute.
* @param string|null $default_namespace Optional. The default namespace if none is explicitly defined.
* @return array An array containing the namespace in the first item and the JSON, the reference path, or null on the
* second item.
*/
private function extract_directive_value( $directive_value, $default_namespace = null ): array {
if ( empty( $directive_value ) || is_bool( $directive_value ) ) {
return array( $default_namespace, null );
}
// Replaces the value and namespace if there is a namespace in the value.
if ( 1 === preg_match( '/^([\w\-_\/]+)::./', $directive_value ) ) {
list($default_namespace, $directive_value) = explode( '::', $directive_value, 2 );
}
/*
* Tries to decode the value as a JSON object. If it fails and the value
* isn't `null`, it returns the value as it is. Otherwise, it returns the
* decoded JSON or null for the string `null`.
*/
$decoded_json = json_decode( $directive_value, true );
if ( null !== $decoded_json || 'null' === $directive_value ) {
$directive_value = $decoded_json;
}
return array( $default_namespace, $directive_value );
}
/**
* Transforms a kebab-case string to camelCase.
*
* @param string $str The kebab-case string to transform to camelCase.
* @return string The transformed camelCase string.
*/
private function kebab_to_camel_case( string $str ): string {
return lcfirst(
preg_replace_callback(
'/(-)([a-z])/',
function ( $matches ) {
return strtoupper( $matches[2] );
},
strtolower( rtrim( $str, '-' ) )
)
);
}
/**
* Processes the `data-wp-interactive` directive.
*
* It adds the default store namespace defined in the directive value to the
* stack so that it's available for the nested interactivity elements.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_interactive_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
// When exiting tags, it removes the last namespace from the stack.
if ( 'exit' === $mode ) {
array_pop( $this->namespace_stack );
return;
}
// Tries to decode the `data-wp-interactive` attribute value.
$attribute_value = $p->get_attribute( 'data-wp-interactive' );
/*
* Pushes the newly defined namespace or the current one if the
* `data-wp-interactive` definition was invalid or does not contain a
* namespace. It does so because the function pops out the current namespace
* from the stack whenever it finds a `data-wp-interactive`'s closing tag,
* independently of whether the previous `data-wp-interactive` definition
* contained a valid namespace.
*/
$new_namespace = null;
if ( is_string( $attribute_value ) && ! empty( $attribute_value ) ) {
$decoded_json = json_decode( $attribute_value, true );
if ( is_array( $decoded_json ) ) {
$new_namespace = $decoded_json['namespace'] ?? null;
} else {
$new_namespace = $attribute_value;
}
}
$this->namespace_stack[] = ( $new_namespace && 1 === preg_match( '/^([\w\-_\/]+)/', $new_namespace ) )
? $new_namespace
: end( $this->namespace_stack );
}
/**
* Processes the `data-wp-context` directive.
*
* It adds the context defined in the directive value to the stack so that
* it's available for the nested interactivity elements.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_context_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
// When exiting tags, it removes the last context from the stack.
if ( 'exit' === $mode ) {
array_pop( $this->context_stack );
return;
}
$attribute_value = $p->get_attribute( 'data-wp-context' );
$namespace_value = end( $this->namespace_stack );
// Separates the namespace from the context JSON object.
list( $namespace_value, $decoded_json ) = is_string( $attribute_value ) && ! empty( $attribute_value )
? $this->extract_directive_value( $attribute_value, $namespace_value )
: array( $namespace_value, null );
/*
* If there is a namespace, it adds a new context to the stack merging the
* previous context with the new one.
*/
if ( is_string( $namespace_value ) ) {
$this->context_stack[] = array_replace_recursive(
end( $this->context_stack ) !== false ? end( $this->context_stack ) : array(),
array( $namespace_value => is_array( $decoded_json ) ? $decoded_json : array() )
);
} else {
/*
* If there is no namespace, it pushes the current context to the stack.
* It needs to do so because the function pops out the current context
* from the stack whenever it finds a `data-wp-context`'s closing tag.
*/
$this->context_stack[] = end( $this->context_stack );
}
}
/**
* Processes the `data-wp-bind` directive.
*
* It updates or removes the bound attributes based on the evaluation of its
* associated reference.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_bind_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
if ( 'enter' === $mode ) {
$all_bind_directives = $p->get_attribute_names_with_prefix( 'data-wp-bind--' );
foreach ( $all_bind_directives as $attribute_name ) {
list( , $bound_attribute ) = $this->extract_prefix_and_suffix( $attribute_name );
if ( empty( $bound_attribute ) ) {
return;
}
$attribute_value = $p->get_attribute( $attribute_name );
$result = $this->evaluate( $attribute_value );
if (
null !== $result &&
(
false !== $result ||
( strlen( $bound_attribute ) > 5 && '-' === $bound_attribute[4] )
)
) {
/*
* If the result of the evaluation is a boolean and the attribute is
* `aria-` or `data-, convert it to a string "true" or "false". It
* follows the exact same logic as Preact because it needs to
* replicate what Preact will later do in the client:
* https://github.com/preactjs/preact/blob/ea49f7a0f9d1ff2c98c0bdd66aa0cbc583055246/src/diff/props.js#L131C24-L136
*/
if (
is_bool( $result ) &&
( strlen( $bound_attribute ) > 5 && '-' === $bound_attribute[4] )
) {
$result = $result ? 'true' : 'false';
}
$p->set_attribute( $bound_attribute, $result );
} else {
$p->remove_attribute( $bound_attribute );
}
}
}
}
/**
* Processes the `data-wp-class` directive.
*
* It adds or removes CSS classes in the current HTML element based on the
* evaluation of its associated references.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_class_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
if ( 'enter' === $mode ) {
$all_class_directives = $p->get_attribute_names_with_prefix( 'data-wp-class--' );
foreach ( $all_class_directives as $attribute_name ) {
list( , $class_name ) = $this->extract_prefix_and_suffix( $attribute_name );
if ( empty( $class_name ) ) {
return;
}
$attribute_value = $p->get_attribute( $attribute_name );
$result = $this->evaluate( $attribute_value );
if ( $result ) {
$p->add_class( $class_name );
} else {
$p->remove_class( $class_name );
}
}
}
}
/**
* Processes the `data-wp-style` directive.
*
* It updates the style attribute value of the current HTML element based on
* the evaluation of its associated references.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_style_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
if ( 'enter' === $mode ) {
$all_style_attributes = $p->get_attribute_names_with_prefix( 'data-wp-style--' );
foreach ( $all_style_attributes as $attribute_name ) {
list( , $style_property ) = $this->extract_prefix_and_suffix( $attribute_name );
if ( empty( $style_property ) ) {
continue;
}
$directive_attribute_value = $p->get_attribute( $attribute_name );
$style_property_value = $this->evaluate( $directive_attribute_value );
$style_attribute_value = $p->get_attribute( 'style' );
$style_attribute_value = ( $style_attribute_value && ! is_bool( $style_attribute_value ) ) ? $style_attribute_value : '';
/*
* Checks first if the style property is not falsy and the style
* attribute value is not empty because if it is, it doesn't need to
* update the attribute value.
*/
if ( $style_property_value || $style_attribute_value ) {
$style_attribute_value = $this->merge_style_property( $style_attribute_value, $style_property, $style_property_value );
/*
* If the style attribute value is not empty, it sets it. Otherwise,
* it removes it.
*/
if ( ! empty( $style_attribute_value ) ) {
$p->set_attribute( 'style', $style_attribute_value );
} else {
$p->remove_attribute( 'style' );
}
}
}
}
}
/**
* Merges an individual style property in the `style` attribute of an HTML
* element, updating or removing the property when necessary.
*
* If a property is modified, the old one is removed and the new one is added
* at the end of the list.
*
* @since 6.5.0
*
* Example:
*
* merge_style_property( 'color:green;', 'color', 'red' ) => 'color:red;'
* merge_style_property( 'background:green;', 'color', 'red' ) => 'background:green;color:red;'
* merge_style_property( 'color:green;', 'color', null ) => ''
*
* @param string $style_attribute_value The current style attribute value.
* @param string $style_property_name The style property name to set.
* @param string|false|null $style_property_value The value to set for the style property. With false, null or an
* empty string, it removes the style property.
* @return string The new style attribute value after the specified property has been added, updated or removed.
*/
private function merge_style_property( string $style_attribute_value, string $style_property_name, $style_property_value ): string {
$style_assignments = explode( ';', $style_attribute_value );
$result = array();
$style_property_value = ! empty( $style_property_value ) ? rtrim( trim( $style_property_value ), ';' ) : null;
$new_style_property = $style_property_value ? $style_property_name . ':' . $style_property_value . ';' : '';
// Generates an array with all the properties but the modified one.
foreach ( $style_assignments as $style_assignment ) {
if ( empty( trim( $style_assignment ) ) ) {
continue;
}
list( $name, $value ) = explode( ':', $style_assignment );
if ( trim( $name ) !== $style_property_name ) {
$result[] = trim( $name ) . ':' . trim( $value ) . ';';
}
}
// Adds the new/modified property at the end of the list.
$result[] = $new_style_property;
return implode( '', $result );
}
/**
* Processes the `data-wp-text` directive.
*
* It updates the inner content of the current HTML element based on the
* evaluation of its associated reference.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_text_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
if ( 'enter' === $mode ) {
$attribute_value = $p->get_attribute( 'data-wp-text' );
$result = $this->evaluate( $attribute_value );
/*
* Follows the same logic as Preact in the client and only changes the
* content if the value is a string or a number. Otherwise, it removes the
* content.
*/
if ( is_string( $result ) || is_numeric( $result ) ) {
$p->set_content_between_balanced_tags( esc_html( $result ) );
} else {
$p->set_content_between_balanced_tags( '' );
}
}
}
/**
* Returns the CSS styles for animating the top loading bar in the router.
*
* @since 6.5.0
*
* @return string The CSS styles for the router's top loading bar animation.
*/
private function get_router_animation_styles(): string {
return <<
HTML;
}
/**
* Processes the `data-wp-router-region` directive.
*
* It renders in the footer a set of HTML elements to notify users about
* client-side navigations. More concretely, the elements added are 1) a
* top loading bar to visually inform that a navigation is in progress
* and 2) an `aria-live` region for accessible navigation announcements.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
*/
private function data_wp_router_region_processor( WP_Interactivity_API_Directives_Processor $p, string $mode ) {
if ( 'enter' === $mode && ! $this->has_processed_router_region ) {
$this->has_processed_router_region = true;
// Initialize the `core/router` store.
$this->state(
'core/router',
array(
'navigation' => array(
'texts' => array(
'loading' => __( 'Loading page, please wait.' ),
'loaded' => __( 'Page Loaded.' ),
),
),
)
);
// Enqueues as an inline style.
wp_register_style( 'wp-interactivity-router-animations', false );
wp_add_inline_style( 'wp-interactivity-router-animations', $this->get_router_animation_styles() );
wp_enqueue_style( 'wp-interactivity-router-animations' );
// Adds the necessary markup to the footer.
add_action( 'wp_footer', array( $this, 'print_router_loading_and_screen_reader_markup' ) );
}
}
/**
* Processes the `data-wp-each` directive.
*
* This directive gets an array passed as reference and iterates over it
* generating new content for each item based on the inner markup of the
* `template` tag.
*
* @since 6.5.0
*
* @param WP_Interactivity_API_Directives_Processor $p The directives processor instance.
* @param string $mode Whether the processing is entering or exiting the tag.
* @param array $tag_stack The reference to the tag stack.
*/
private function data_wp_each_processor( WP_Interactivity_API_Directives_Processor $p, string $mode, array &$tag_stack ) {
if ( 'enter' === $mode && 'TEMPLATE' === $p->get_tag() ) {
$attribute_name = $p->get_attribute_names_with_prefix( 'data-wp-each' )[0];
$extracted_suffix = $this->extract_prefix_and_suffix( $attribute_name );
$item_name = isset( $extracted_suffix[1] ) ? $this->kebab_to_camel_case( $extracted_suffix[1] ) : 'item';
$attribute_value = $p->get_attribute( $attribute_name );
$result = $this->evaluate( $attribute_value );
// Gets the content between the template tags and leaves the cursor in the closer tag.
$inner_content = $p->get_content_between_balanced_template_tags();
// Checks if there is a manual server-side directive processing.
$template_end = 'data-wp-each: template end';
$p->set_bookmark( $template_end );
$p->next_tag();
$manual_sdp = $p->get_attribute( 'data-wp-each-child' );
$p->seek( $template_end ); // Rewinds to the template closer tag.
$p->release_bookmark( $template_end );
/*
* It doesn't process in these situations:
* - Manual server-side directive processing.
* - Empty or non-array values.
* - Associative arrays because those are deserialized as objects in JS.
* - Templates that contain top-level texts because those texts can't be
* identified and removed in the client.
*/
if (
$manual_sdp ||
empty( $result ) ||
! is_array( $result ) ||
! array_is_list( $result ) ||
! str_starts_with( trim( $inner_content ), '<' ) ||
! str_ends_with( trim( $inner_content ), '>' )
) {
array_pop( $tag_stack );
return;
}
// Extracts the namespace from the directive attribute value.
$namespace_value = end( $this->namespace_stack );
list( $namespace_value ) = is_string( $attribute_value ) && ! empty( $attribute_value )
? $this->extract_directive_value( $attribute_value, $namespace_value )
: array( $namespace_value, null );
// Processes the inner content for each item of the array.
$processed_content = '';
foreach ( $result as $item ) {
// Creates a new context that includes the current item of the array.
$this->context_stack[] = array_replace_recursive(
end( $this->context_stack ) !== false ? end( $this->context_stack ) : array(),
array( $namespace_value => array( $item_name => $item ) )
);
// Processes the inner content with the new context.
$processed_item = $this->_process_directives( $inner_content );
if ( null === $processed_item ) {
// If the HTML is unbalanced, stop processing it.
array_pop( $this->context_stack );
return;
}
// Adds the `data-wp-each-child` to each top-level tag.
$i = new WP_Interactivity_API_Directives_Processor( $processed_item );
while ( $i->next_tag() ) {
$i->set_attribute( 'data-wp-each-child', true );
$i->next_balanced_tag_closer_tag();
}
$processed_content .= $i->get_updated_html();
// Removes the current context from the stack.
array_pop( $this->context_stack );
}
// Appends the processed content after the tag closer of the template.
$p->append_content_after_template_tag_closer( $processed_content );
// Pops the last tag because it skipped the closing tag of the template tag.
array_pop( $tag_stack );
}
}
}