Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parser/do dynamic blocks with inner blocks #11227

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
131 changes: 49 additions & 82 deletions lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,25 +150,45 @@ function get_dynamic_blocks_regex() {
* @since 1.9.0
*
* @param array $block A single parsed block object.
* @param array $inner_blocks A list of processed inner blocks.
* @return string String of rendered HTML.
*/
function gutenberg_render_block( $block ) {
$block_name = isset( $block['blockName'] ) ? $block['blockName'] : null;
$attributes = is_array( $block['attrs'] ) ? $block['attrs'] : array();
$raw_content = isset( $block['innerHTML'] ) ? $block['innerHTML'] : null;

if ( $block_name ) {
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_name );
if ( null !== $block_type && $block_type->is_dynamic() ) {
return $block_type->render( $attributes );
function gutenberg_render_block( $block, $inner_blocks = [] ) {
$block_name = isset( $block['blockName'] ) ? $block['blockName'] : null;
$block_type = $block_name ? WP_Block_Type_Registry::get_instance()->get_registered( $block_name ) : null;
$attributes = is_array( $block['attrs'] ) ? $block['attrs'] : array();

// If there are innerBlocks, stitch their results back in.
if ( ! empty( $block['blockMarkers' ] ) ) {
$output = '';
$index = 0;
foreach( $block['blockMarkers'] as $i => $p ) {
$output .= substr( $block['innerHTML'], $index, $p - $index );
$output .= $inner_blocks[ $i ];
$index = $p;
}
$output .= substr( $block['innerHTML'], $index );

$block['innerHTML'] = $output;
}

if ( $raw_content ) {
return $raw_content;
// Handle both dynamic and static.
if ( null !== $block_type && $block_type->is_dynamic() ) {
return $block_type->render( $attributes, $block['innerHTML'] );
}
return $block['innerHTML'];
}

return '';
if ( ! class_exists( 'BlockRecursiveIteratorFilter' ) ) {
class BlockRecursiveIteratorFilter extends RecursiveFilterIterator {
public function accept() {
return is_array( $this->current() );
}

public function getChildren() {
return new self( new RecursiveArrayIterator( $this->current()['innerBlocks'] ) );
}
}
}

if ( ! function_exists( 'do_blocks' ) ) {
Expand All @@ -183,84 +203,31 @@ function gutenberg_render_block( $block ) {
*/
function do_blocks( $content ) {
global $post;

$rendered_content = '';
$dynamic_block_pattern = get_dynamic_blocks_regex();

/*
* Back up global post, to restore after render callback.
* Allows callbacks to run new WP_Query instances without breaking the global post.
*/
$global_post = $post;

while ( preg_match( $dynamic_block_pattern, $content, $block_match, PREG_OFFSET_CAPTURE ) ) {
$opening_tag = $block_match[0][0];
$offset = $block_match[0][1];
$block_name = $block_match[1][0];
$is_self_closing = isset( $block_match[4] );

// Reset attributes JSON to prevent scope bleed from last iteration.
$block_attributes_json = null;
if ( isset( $block_match[3] ) ) {
$block_attributes_json = $block_match[3][0];
}

// Since content is a working copy since the last match, append to
// rendered content up to the matched offset...
$rendered_content .= substr( $content, 0, $offset );

// ...then update the working copy of content.
$content = substr( $content, $offset + strlen( $opening_tag ) );

// Make implicit core namespace explicit.
$is_implicit_core_namespace = ( false === strpos( $block_name, '/' ) );
$normalized_block_name = $is_implicit_core_namespace ? 'core/' . $block_name : $block_name;

// Find registered block type. We can assume it exists since we use the
// `get_dynamic_block_names` function as a source for pattern matching.
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $normalized_block_name );

// Attempt to parse attributes JSON, if available.
$attributes = array();
if ( ! empty( $block_attributes_json ) ) {
$decoded_attributes = json_decode( $block_attributes_json, true );
if ( ! is_null( $decoded_attributes ) ) {
$attributes = $decoded_attributes;
}
$blocks = gutenberg_parse_blocks( $content );
$rai = new RecursiveArrayIterator( $blocks );
$rfi = new BlockRecursiveIteratorFilter( $rai );
$rii = new RecursiveIteratorIterator( $rfi, RecursiveIteratorIterator::CHILD_FIRST );
$stack = array();

foreach ( $rii as $block ) {
if ( ! empty( $block['innerBlocks'] ) ) {
$inner_blocks = array_splice( $stack, -1 * count( $block['innerBlocks'] ) );
$stack[] = gutenberg_render_block( $block, $inner_blocks );
} else {
$stack[] = gutenberg_render_block( $block );
}

$inner_content = '';

if ( ! $is_self_closing ) {
$end_tag_pattern = '/<!--\s+\/wp:' . str_replace( '/', '\/', preg_quote( $block_name ) ) . '\s+-->/';
if ( ! preg_match( $end_tag_pattern, $content, $block_match_end, PREG_OFFSET_CAPTURE ) ) {
// If no closing tag is found, abort all matching, and continue
// to append remainder of content to rendered output.
break;
}

// Update content to omit text up to and including closing tag.
$end_tag = $block_match_end[0][0];
$end_offset = $block_match_end[0][1];

$inner_content = substr( $content, 0, $end_offset );
$content = substr( $content, $end_offset + strlen( $end_tag ) );
}

// Replace dynamic block with server-rendered output.
$rendered_content .= $block_type->render( $attributes, $inner_content );

// Restore global $post.
$post = $global_post;
}

// Append remaining unmatched content.
$rendered_content .= $content;

// Strip remaining block comment demarcations.
$rendered_content = preg_replace( '/<!--\s+\/?wp:.*?-->\r?\n?/m', '', $rendered_content );
$output = '';
foreach( $stack as $block ) {
$output .= $block;
}

return $rendered_content;
return $output;
}

add_filter( 'the_content', 'do_blocks', 7 ); // BEFORE do_shortcode() and oembed.
Expand Down
56 changes: 35 additions & 21 deletions lib/parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,20 +259,22 @@ private function peg_f1($pre, $bs, $post) { return peg_join_blocks( $pre, $bs, $
private function peg_f2($blockName, $a) { return $a; }
private function peg_f3($blockName, $attrs) {
return array(
'blockName' => $blockName,
'attrs' => isset( $attrs ) ? $attrs : array(),
'innerBlocks' => array(),
'innerHTML' => '',
'blockName' => $blockName,
'attrs' => isset( $attrs ) ? $attrs : array(),
'innerBlocks' => array(),
'innerHTML' => '',
'blockMarkers' => array(),
);
}
private function peg_f4($s, $children, $e) {
list( $innerHTML, $innerBlocks ) = peg_array_partition( $children, 'is_string' );
list( $innerHTML, $innerBlocks, $blockMarkers ) = peg_array_partition( $children );

return array(
'blockName' => $s['blockName'],
'attrs' => $s['attrs'],
'innerBlocks' => $innerBlocks,
'innerHTML' => implode( '', $innerHTML ),
'blockMarkers' => $blockMarkers,
);
}
private function peg_f5($blockName, $attrs) {
Expand Down Expand Up @@ -1440,19 +1442,31 @@ public function parse($input) {
// The `maybeJSON` function is not needed in PHP because its return semantics
// are the same as `json_decode`

if ( ! function_exists( 'ucs2length' ) ) {
function ucs2length( $string ) {
return (int) strlen( iconv( 'UTF-8', 'UTF-16le', $string ) ) / 2;
}
}

// array arguments are backwards because of PHP
if ( ! function_exists( 'peg_array_partition' ) ) {
function peg_array_partition( $array, $predicate ) {
$truthy = array();
$falsey = array();
function peg_array_partition( $array ) {
$truthy = array();
$falsey = array();
$markers = array();
$offset = 0;

foreach ( $array as $item ) {
call_user_func( $predicate, $item )
? $truthy[] = $item
: $falsey[] = $item;
if ( is_string( $item ) ) {
$offset += ucs2length( $item );
$truthy[] = $item;
} else {
$markers[] = $offset;
$falsey[] = $item;
}
}

return array( $truthy, $falsey );
return array( $truthy, $falsey, $markers );
}
}

Expand All @@ -1462,10 +1476,10 @@ function peg_join_blocks( $pre, $tokens, $post ) {

if ( ! empty( $pre ) ) {
$blocks[] = array(
'blockName' => null,
'attrs' => array(),
'blockName' => null,
'attrs' => array(),
'innerBlocks' => array(),
'innerHTML' => $pre
'innerHTML' => $pre
);
}

Expand All @@ -1476,20 +1490,20 @@ function peg_join_blocks( $pre, $tokens, $post ) {

if ( ! empty( $html ) ) {
$blocks[] = array(
'blockName' => null,
'attrs' => array(),
'blockName' => null,
'attrs' => array(),
'innerBlocks' => array(),
'innerHTML' => $html
'innerHTML' => $html
);
}
}

if ( ! empty( $post ) ) {
$blocks[] = array(
'blockName' => null,
'attrs' => array(),
'blockName' => null,
'attrs' => array(),
'innerBlocks' => array(),
'innerHTML' => $post
'innerHTML' => $post
);
}

Expand Down
49 changes: 37 additions & 12 deletions packages/block-serialization-default-parser/parser.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,20 @@ class WP_Block_Parser_Block {
*/
public $innerHTML;

function __construct( $name, $attrs, $innerBlocks, $innerHTML ) {
$this->blockName = $name;
$this->attrs = $attrs;
$this->innerBlocks = $innerBlocks;
$this->innerHTML = $innerHTML;
/**
* Indices into innerHTML where innerBlocks were found, UCS2-length indices
*
* @since 5.0.0
* @var int[]
*/
public $blockMarkers;

function __construct( $name, $attrs, $innerBlocks, $innerHTML, $blockMarkers ) {
$this->blockName = $name;
$this->attrs = $attrs;
$this->innerBlocks = $innerBlocks;
$this->innerHTML = $innerHTML;
$this->blockMarkers = $blockMarkers;
}
}

Expand Down Expand Up @@ -252,14 +261,14 @@ function proceed() {
) );
}

$this->output[] = (array) new WP_Block_Parser_Block( $block_name, $attrs, array(), '' );
$this->output[] = (array) new WP_Block_Parser_Block( $block_name, $attrs, array(), '', array() );
$this->offset = $start_offset + $token_length;
return true;
}

// otherwise we found an inner block
$this->add_inner_block(
new WP_Block_Parser_Block( $block_name, $attrs, array(), '' ),
new WP_Block_Parser_Block( $block_name, $attrs, array(), '', array() ),
$start_offset,
$token_length
);
Expand All @@ -269,7 +278,7 @@ function proceed() {
case 'block-opener':
// track all newly-opened blocks on the stack
array_push( $this->stack, new WP_Block_Parser_Frame(
new WP_Block_Parser_Block( $block_name, $attrs, array(), '' ),
new WP_Block_Parser_Block( $block_name, $attrs, array(), '', array() ),
$start_offset,
$token_length,
$start_offset + $token_length,
Expand Down Expand Up @@ -403,10 +412,15 @@ function next_token() {
* @since 3.9.0
*
* @param string $innerHTML HTML content of block
* @return WP_Block_Parser_Block freeform block object
* @return array freeform block object
*/
static function freeform( $innerHTML ) {
return new WP_Block_Parser_Block( null, array(), array(), $innerHTML );
return array(
'blockName' => null,
'attrs' => array(),
'innerBlocks' => array(),
'innerHTML' => $innerHTML,
);
}

/**
Expand Down Expand Up @@ -440,8 +454,15 @@ function add_freeform( $length = null ) {
*/
function add_inner_block( WP_Block_Parser_Block $block, $token_start, $token_length, $last_offset = null ) {
$parent = $this->stack[ count( $this->stack ) - 1 ];
$parent->block->innerBlocks[] = $block;
$parent->block->innerHTML .= substr( $this->document, $parent->prev_offset, $token_start - $parent->prev_offset );

$next_html = substr( $this->document, $parent->prev_offset, $token_start - $parent->prev_offset );
$prev_length = ! empty( $parent->block->blockMarkers )
? $parent->block->blockMarkers[ count( $parent->block->blockMarkers ) - 1 ]
: 0;

$parent->block->innerBlocks[] = (array) $block;
$parent->block->blockMarkers[] = $prev_length + self::ucs2length( $next_html );
$parent->block->innerHTML .= $next_html;
$parent->prev_offset = $last_offset ? $last_offset : $token_start + $token_length;
}

Expand Down Expand Up @@ -470,4 +491,8 @@ function add_block_from_stack( $end_offset = null ) {

$this->output[] = (array) $stack_top->block;
}

static function ucs2length( $string ) {
return (int) strlen( iconv( 'UTF-8', 'UTF-16le', $string ) ) / 2;
}
}
Loading