Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,6 @@ public function select(DOMElement $select, bool $forceNative = false, ?DOMElemen
), $select);
}

$generator = new AuthoredSelectBlockGenerator();
$registry = $this->session->requireGeneratedBlockRegistry();
$registry->register(AuthoredSelectBlockGenerator::class, $generator->definition($registry->namespace()));
$attrs = array_filter(array(
'id' => SourceDom::attr($select, 'id'),
'name' => SourceDom::attr($select, 'name'),
Expand All @@ -153,19 +150,24 @@ public function select(DOMElement $select, bool $forceNative = false, ?DOMElemen
'disabled' => $select->hasAttribute('disabled'),
), static fn (mixed $value): bool => is_array($value) ? array() !== $value : '' !== $value);
$attrs = array_replace($attrs, $state ?? array());
// Capture-backed controls have an explicit state contract for the core
// option-list renderer. Ordinary authored controls must keep their saved
// native markup (including form submission and source CSS topology).
if (null !== $state) {
return $this->nativeSelect($attrs, $select);
}
$generator = new AuthoredSelectBlockGenerator();
$registry = $this->session->requireGeneratedBlockRegistry();
$registry->register(AuthoredSelectBlockGenerator::class, $generator->definition($registry->namespace()));
$markup = $generator->markup($attrs);
$controlBlock = array(
return array(
'blockName' => $registry->blockName(AuthoredSelectBlockGenerator::LOCAL_NAME),
'attrs' => $attrs,
'innerBlocks' => array(),
'innerHTML' => $markup,
'innerContent' => array( $markup ),
// Anchor-only identity: lets a finding bind this control's block
// without registering it as a provenance source.
'innerContent' => array($markup),
'_source_anchor_selector' => SourceDom::elementSelector($select),
);

return $controlBlock;
}

public function listbox(DOMElement $trigger, ?DOMElement $panel = null): ?array
Expand Down Expand Up @@ -214,9 +216,6 @@ public function listbox(DOMElement $trigger, ?DOMElement $panel = null): ?array
if (array() === $selected && '' !== $triggerLabel && !in_array($triggerLabel, array_column($options, 'label'), true)) {
array_unshift($options, array('label' => $triggerLabel, 'value' => '', 'selected' => true, 'disabled' => true, 'placeholder' => true));
}
$generator = new AuthoredSelectBlockGenerator();
$registry = $this->session->requireGeneratedBlockRegistry();
$registry->register(AuthoredSelectBlockGenerator::class, $generator->definition($registry->namespace()));
$attrs = array_filter(array(
'id' => SourceDom::attr($trigger, 'id'),
'name' => SourceDom::attr($trigger, 'name'),
Expand All @@ -226,11 +225,32 @@ public function listbox(DOMElement $trigger, ?DOMElement $panel = null): ?array
'options' => $options,
'placeholder' => $triggerLabel,
), static fn (mixed $value): bool => is_array($value) ? array() !== $value : '' !== $value);
$markup = $generator->markup($attrs);
$control = BlockFactory::leaf($registry->blockName(AuthoredSelectBlockGenerator::LOCAL_NAME), $attrs, $markup);
$control = $this->nativeSelect($attrs, $trigger);
return $this->createBlock->createBlock('core/group', array('className' => 'blocks-engine-authored-select-wrapper'), array($control), null);
}

/**
* Core list items own editable option labels and ordering. Native semantics
* are metadata, consumed by the theme renderer instead of a companion block.
* @param array<string, mixed> $attrs
*/
private function nativeSelect(array $attrs, DOMElement $source): array
{
$items = array();
foreach ($attrs['options'] ?? array() as $option) {
$label = (string) ($option['label'] ?? '');
unset($option['label']);
$items[] = $this->createBlock->createBlock('core/list-item', array(
'content' => $this->runtime->escapeHtml($label),
'metadata' => array('blocksEngineSelectOption' => $option),
));
}
unset($attrs['options'], $attrs['selectedSummary']);
return $this->createBlock->createBlock('core/list', array(
'metadata' => array('blocksEngineSelect' => $attrs),
), $items, $source);
}

/**
* Return a compact native input only when the resolved cascade proves
* authored presentation that a readable paragraph cannot retain.
Expand Down
47 changes: 47 additions & 0 deletions php-transformer/src/WordPressSitePlan/NativeSelectRuntime.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);

namespace Automattic\BlocksEngine\PhpTransformer\WordPressSitePlan;

/** Front-end native semantics for editable core option lists. */
final class NativeSelectRuntime
{
public static function source(): string
{
return <<<'PHP'
add_filter( 'render_block_core/list', static function ( string $content, array $block ): string {
$attrs = $block['attrs']['metadata']['blocksEngineSelect'] ?? null;
if ( ! is_array( $attrs ) ) return $content;
$html = '<select';
foreach ( array( 'id', 'name', 'form', 'size', 'ariaLabel', 'placeholder', 'className', 'style' ) as $key ) {
if ( '' !== (string) ( $attrs[$key] ?? '' ) ) $html .= ' ' . ( array( 'className' => 'class', 'ariaLabel' => 'aria-label' )[$key] ?? $key ) . '="' . esc_attr( $attrs[$key] ) . '"';
}
foreach ( array( 'required', 'disabled', 'multiple' ) as $key ) if ( ! empty( $attrs[$key] ) ) $html .= ' ' . $key;
foreach ( $attrs['dataAttributes'] ?? array() as $name => $value ) {
if ( preg_match( '/^data-(?!wp-)[a-z0-9_.:-]+$/D', $name ) && ! str_starts_with( $name, 'data-blocks-engine-' ) ) $html .= ' ' . $name . '="' . esc_attr( $value ) . '"';
}
$options = ''; $state = array(); $has_state = false; $group = 0;
foreach ( $block['innerBlocks'] ?? array() as $item ) {
if ( 'core/list-item' !== ( $item['blockName'] ?? '' ) ) continue;
$option = $item['attrs']['metadata']['blocksEngineSelectOption'] ?? array();
// Read the saved core label, so editor changes are the native label too.
$label = html_entity_decode( wp_strip_all_tags( $item['innerHTML'] ?? '' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
$next = $option['group']['index'] ?? 0;
if ( $next !== $group ) {
if ( $group ) $options .= '</optgroup>';
if ( $next ) $options .= '<optgroup label="' . esc_attr( $option['group']['label'] ?? '' ) . '"' . ( ! empty( $option['group']['disabled'] ) ? ' disabled' : '' ) . '>';
$group = $next;
}
$options .= '<option' . ( false === ( $option['valueDeclared'] ?? true ) ? '' : ' value="' . esc_attr( $option['value'] ?? $label ) . '"' ) . ( ! empty( $option['selected'] ) ? ' selected' : '' ) . ( ! empty( $option['disabled'] ) ? ' disabled' : '' ) . '>' . esc_html( $label ) . '</option>';
$has_state = $has_state || array_key_exists( 'initialSelected', $option );
$state[] = array( 'selected' => $option['initialSelected'] ?? ! empty( $option['selected'] ), 'defaultSelected' => ! empty( $option['selected'] ) );
}
if ( $group ) $options .= '</optgroup>';
if ( $has_state ) $html .= ' data-blocks-engine-control-state="' . esc_attr( wp_json_encode( array( 'version' => 1, 'kind' => 'select', 'options' => $state ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) ) . '"';
$html .= '>' . $options . '</select>';
if ( ! empty( $attrs['label'] ) ) $html = '<label' . ( ! empty( $attrs['labelClassName'] ) ? ' class="' . esc_attr( $attrs['labelClassName'] ) . '"' : '' ) . ( ! empty( $attrs['labelStyle'] ) ? ' style="' . esc_attr( $attrs['labelStyle'] ) . '"' : '' ) . '>' . wp_kses_post( ! empty( $attrs['labelMarkup'] ) ? $attrs['labelMarkup'] : esc_html( $attrs['label'] ) ) . $html . '</label>';
return $html;
}, 10, 2 );
PHP;
}
}
6 changes: 6 additions & 0 deletions php-transformer/src/WordPressSitePlan/ThemeBootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,12 @@ public static function functionsPhp(array $assets, array $scripts = array(), arr
$headerOffsetScript = NavigationHeaderOffsetRuntime::script();
$lines[] = "add_action( 'wp_enqueue_scripts', static function (): void { wp_register_script( 'blocks-engine-navigation-header-offset', false, array(), null, true ); wp_enqueue_script( 'blocks-engine-navigation-header-offset' ); wp_add_inline_script( 'blocks-engine-navigation-header-offset', " . var_export($headerOffsetScript, true) . " ); } );";
}
if (self::markupContains($documentsWithMenus, 'blocksEngineSelect')) {
$lines[] = NativeSelectRuntime::source();
$selectStateScript = \Automattic\BlocksEngine\PhpTransformer\WordPress\AuthoredControlStateScript::viewScript();
$lines[] = "add_action( 'wp_enqueue_scripts', static function (): void { wp_register_script( 'blocks-engine-select-state', false, array(), null, true ); wp_enqueue_script( 'blocks-engine-select-state' ); wp_add_inline_script( 'blocks-engine-select-state', " . var_export($selectStateScript, true) . " ); } );";
$lines[] = "add_action( 'wp_enqueue_scripts', static function (): void { wp_register_style( 'blocks-engine-select-wrapper', false ); wp_enqueue_style( 'blocks-engine-select-wrapper' ); wp_add_inline_style( 'blocks-engine-select-wrapper', '.wp-block-group.blocks-engine-authored-select-wrapper{display:contents}' ); } );";
}
$breadcrumbLabels = BreadcrumbLabelRuntime::labels($documents, $pages);
$breadcrumbPostTrails = BreadcrumbLabelRuntime::postTrails($pages);
if (array() !== $breadcrumbLabels || array() !== $breadcrumbPostTrails) $lines[] = BreadcrumbLabelRuntime::source($breadcrumbLabels, $breadcrumbPostTrails);
Expand Down
40 changes: 40 additions & 0 deletions php-transformer/tests/Support/NativeSelectRendererFixture.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);

namespace Automattic\BlocksEngine\PhpTransformer\Tests\Support;

use Automattic\BlocksEngine\PhpTransformer\WordPress\Runtime;
use Automattic\BlocksEngine\PhpTransformer\WordPressSitePlan\NativeSelectRuntime;

/** Execute the generated theme filter with an isolated WordPress escaping surface. */
final class NativeSelectRendererFixture
{
public static mixed $filter = null;

public static function render(string $markup): string
{
if (null === self::$filter) {
eval('namespace ' . __NAMESPACE__ . ';' . NativeSelectRuntime::source());
}
$runtime = new Runtime();
$render = static function (array $block) use (&$render): string {
if (isset($block['attrs']['metadata']['blocksEngineSelect'])) {
return (self::$filter)('', $block);
}
$content = '';
$children = $block['innerBlocks'] ?? array();
foreach ($block['innerContent'] ?? array($block['innerHTML'] ?? '') as $part) {
$content .= null === $part ? $render(array_shift($children)) : $part;
}
return $content;
};
return implode('', array_map($render, $runtime->parseBlocks($markup)));
}
}

function add_filter($name, $callback, ...$args) { NativeSelectRendererFixture::$filter = $callback; }
function esc_attr($text) { return htmlspecialchars((string) $text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function esc_html($text) { return esc_attr($text); }
function wp_strip_all_tags($text) { return strip_tags($text); }
function wp_json_encode($data, $flags = 0) { return json_encode($data, $flags); }
function wp_kses_post($text) { return $text; }
6 changes: 4 additions & 2 deletions php-transformer/tests/contract/component-interactions.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,14 @@
$html = $markup($result);
$assert(!isset($report['pages'][0]['states']), 'Real emitter fixture has one component inventory.');
$assert(array('dialog', 'listbox', 'tabs', 'disclosure', 'carousel', 'unsupported') === array_column($report['pages'][0]['components'], 'kind'), 'Real capture covers all six surfaces.');
foreach (array('custom/authored-select', 'tabs', 'tab-list', 'tab-panels', 'tab-panel', 'details', 'custom/authored-carousel') as $block) {
foreach (array('tabs', 'tab-list', 'tab-panels', 'tab-panel', 'details', 'custom/authored-carousel') as $block) {
$assert(str_contains($html, '<!-- wp:' . $block . ' ') || str_contains($html, '<!-- wp:' . $block . ' -->'), $block . ' keeps its pre-migration native block family.');
}
$assert(!str_contains($html, '<!-- wp:custom/captured-dialog') && str_contains($html, '<!-- wp:group ') && str_contains($html, '"blocksEngineDialog":'), 'Dialog content uses an editable core Group rather than a companion block.');
$assert(str_contains($html, '"data-blocks-engine-triggers":"open-dialog"') && str_contains($html, '"data-blocks-engine-resting":"hidden"'), 'Dialog retains its native trigger binding and closed resting state.');
$assert(str_contains($html, '<option value="Small" selected>Small</option>') && str_contains($html, '<option value="Large">Large</option>'), 'Listbox retains native selection behavior.');
$assert(str_contains($html, '"blocksEngineSelect":') && !str_contains($html, '<!-- wp:custom/authored-select'), 'Listbox choices use editable core blocks without a select companion.');
$rendered = \Automattic\BlocksEngine\PhpTransformer\Tests\Support\NativeSelectRendererFixture::render($html);
$assert(str_contains($rendered, '<option value="Small" selected>Small</option>') && str_contains($rendered, '<option value="Large">Large</option>'), 'Listbox retains native selection behavior.');
$assert(2 === substr_count($html, '<!-- wp:tab-panel ') && str_contains($html, 'Lazy observed content'), 'Lazy tab is editable native panel content.');
$assert(str_contains($html, '"showContent":true') && str_contains($html, '<details id="disclosure" class="wp-block-details" open>'), 'Authored open disclosure stays open.');
$assert(str_contains($html, '"slideCount":2') && str_contains($html, '"initialSlide":0') && str_contains($html, 'actions.next'), 'Carousel retains its initial frame and native directional runtime.');
Expand Down
10 changes: 5 additions & 5 deletions php-transformer/tests/contract/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -2533,7 +2533,7 @@ public function recognize(DOMElement $element, PatternContext $context): ?Patter
$assert(str_contains((string) ($standaloneControls['serialized_blocks'] ?? ''), '<select id="product-sort" name="products" placeholder="Sort products" class="catalog-sort">'), 'compact select preserves native id, name, placeholder, and CSS selector identity');
$assert(1 === substr_count((string) ($standaloneControls['serialized_blocks'] ?? ''), '>Sort products</label>') && str_contains((string) ($standaloneControls['serialized_blocks'] ?? ''), '<label for="product-sort"'), 'styled select emits its source associated label exactly once without a duplicate wrapping label');
$assert(! str_contains((string) ($standaloneControls['serialized_blocks'] ?? ''), '<!-- wp:html') || str_contains((string) ($standaloneControls['serialized_blocks'] ?? ''), '<select class="js-sort-select"'), 'only the runtime-targeted select uses core/html');
$assert(1 === preg_match('/<select[^>]*\\sclass="js-sort-select"/', (string) ($standaloneControls['serialized_blocks'] ?? '')), 'runtime-targeted select preserves native markup in serialized blocks');
$assert(1 === preg_match('/<select[^>]*\\sclass="js-sort-select"/', (string) ($standaloneControls['serialized_blocks'] ?? '')), 'runtime-targeted select renders native markup from core options');
$assert(str_contains((string) ($standaloneControls['serialized_blocks'] ?? ''), 'id="donation"'), 'readable input output preserves source id as a block anchor');
$assert(str_contains((string) ($standaloneControls['serialized_blocks'] ?? ''), 'js-sort-select'), 'runtime-targeted select keeps behavior-hook class on native markup');
$assert(1 === count($standaloneControls['source_reports']['runtime_islands'] ?? array()), 'runtime islands report only the explicitly runtime-targeted standalone control');
Expand Down Expand Up @@ -2701,7 +2701,7 @@ public function recognize(DOMElement $element, PatternContext $context): ?Patter
array('runtime_dom_selectors' => array('#scheme-select', '#crt-toggle'))
)->toArray();
$labelWrappedRuntimeMarkup = (string) ($labelWrappedRuntimeControls['serialized_blocks'] ?? '');
$assert(str_contains($labelWrappedRuntimeMarkup, '<select id="scheme-select"'), 'label-wrapped runtime select preserves exact native DOM target');
$assert(str_contains(\Automattic\BlocksEngine\PhpTransformer\Tests\Support\NativeSelectRendererFixture::render($labelWrappedRuntimeMarkup), '<select id="scheme-select"'), 'label-wrapped runtime select preserves exact native DOM target');
$assert(str_contains($labelWrappedRuntimeMarkup, '<input type="checkbox" id="crt-toggle"'), 'label-wrapped runtime checkbox preserves exact native DOM target');

$artifactControlSelectors = ( new ArtifactCompiler() )->compile(
Expand Down Expand Up @@ -5927,12 +5927,12 @@ public function recognize(DOMElement $element, PatternContext $context): ?Patter
$authoredSelectCompanion = $authoredControlBlocks[0] ?? array();
$authoredInputCompanion = $authoredControlBlocks[1] ?? array();
$assert('custom/authored-select' === ($authoredSelectCompanion['block_json']['name'] ?? null), 'authored-select companion metadata uses its canonical block name');
$assert('custom/authored-input' === ($authoredInputCompanion['block_json']['name'] ?? null), 'authored-input companion metadata uses its canonical block name');
$assert(array( 'index.js' => array( 'wp-blocks', 'wp-block-editor', 'wp-components', 'wp-element', 'wp-rich-text' ) ) === ($authoredSelectCompanion['script_dependencies'] ?? null), 'authored-select companion dependency metadata survives payload compilation');
$assert(array( 'index.js' => array( 'wp-blocks', 'wp-block-editor', 'wp-components', 'wp-data', 'wp-element', 'wp-rich-text' ) ) === ($authoredInputCompanion['script_dependencies'] ?? null), 'authored-input companion dependency metadata survives payload compilation');
preg_match_all("/registerBlockType\\(\\s*'([^']+)'/", (string) ($authoredSelectCompanion['assets']['index.js'] ?? ''), $authoredSelectRegistrations);
preg_match_all("/registerBlockType\\(\\s*'([^']+)'/", (string) ($authoredInputCompanion['assets']['index.js'] ?? ''), $authoredInputRegistrations);
$assert(array( 'custom/authored-select' ) === ($authoredSelectRegistrations[1] ?? array()), 'authored-select companion editor script registers only its canonical block name');
$assert('custom/authored-input' === ($authoredInputCompanion['block_json']['name'] ?? null), 'authored-input companion metadata uses its canonical block name');
$assert(array( 'index.js' => array( 'wp-blocks', 'wp-block-editor', 'wp-components', 'wp-data', 'wp-element', 'wp-rich-text' ) ) === ($authoredInputCompanion['script_dependencies'] ?? null), 'authored-input companion dependency metadata survives payload compilation');
preg_match_all("/registerBlockType\\(\\s*'([^']+)'/", (string) ($authoredInputCompanion['assets']['index.js'] ?? ''), $authoredInputRegistrations);
$assert(array( 'custom/authored-input' ) === ($authoredInputRegistrations[1] ?? array()), 'authored-input companion editor script registers only its canonical block name');

$scriptCompanion = $compiler->compile(
Expand Down
4 changes: 2 additions & 2 deletions php-transformer/tests/unit/authored-select-block.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,8 @@ function walk( node ) { if ( ! node || 'object' !== typeof node ) return null; i
. '</div></form>'
)->toArray();
$listboxMarkup = (string) ( $listboxResult['serialized_blocks'] ?? '' );
$assert(str_contains($listboxMarkup, 'authored-select'), 'captured listbox trigger uses the editable native select companion');
$assert(str_contains($listboxMarkup, '<option value="Canada" selected>Canada</option>'), 'captured listbox materialization carries the selected value and label');
$assert(str_contains($listboxMarkup, 'blocksEngineSelect'), 'captured listbox trigger uses an editable core option list');
$assert(str_contains($listboxMarkup, '"value":"Canada","selected":true') && str_contains($listboxMarkup, '>Canada</li>'), 'captured listbox materialization carries the selected value and label');
$assert(!str_contains($listboxMarkup, 'core/details'), 'captured listbox is not degraded to a disclosure block');

$disabledAttrs = array(
Expand Down
Loading
Loading