*/
private function block(DOMElement $element, array &$fallbacks): array
{
- $registry = $this->session->requireGeneratedBlockRegistry()
- ?? throw new LogicException('Generated block registry has not been prepared for this transform.');
- $blockName = $registry->blockName(CapturedChoiceGroupBlockGenerator::LOCAL_NAME);
- $registry->register(CapturedChoiceGroupBlockGenerator::class, (new CapturedChoiceGroupBlockGenerator())->definition($blockName));
-
$config = trim(SourceDom::attr($element, 'data-blocks-engine-choice-config'));
$decoded = json_decode($config, true);
if (! is_array($decoded) || ! is_array($decoded['states'] ?? null) || array() === $decoded['states']) {
@@ -104,20 +97,31 @@ private function block(DOMElement $element, array &$fallbacks): array
$children = $this->withoutStateClassTokens($children, $statePresentation['tokens']);
}
$escape = static fn(string $value): string => htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
- $opening = '<' . $tagName;
- if ('' !== ($attrs['anchor'] ?? '')) $opening .= ' id="' . $escape((string) $attrs['anchor']) . '"';
- if ('' !== ($attrs['className'] ?? '')) $opening .= ' class="' . $escape((string) $attrs['className']) . '"';
- if ('' !== ($attrs['ariaLabel'] ?? '')) $opening .= ' aria-label="' . $escape((string) $attrs['ariaLabel']) . '"';
- $opening .= ' data-blocks-engine-choice-group="true" data-blocks-engine-choice-config="' . $escape($config) . '">';
- $innerContent = array($opening);
+ // Save canonical Group markup. The source shell is front-end behavior,
+ // not a new block type: core owns the container and its editable children.
+ $groupAttrs = array('metadata' => array('blocksEngineChoiceGroup' => array(
+ 'tagName' => $tagName,
+ 'attributes' => array_filter(array(
+ 'id' => $attrs['anchor'] ?? '',
+ 'class' => $attrs['className'] ?? '',
+ 'aria-label' => $attrs['ariaLabel'] ?? '',
+ 'data-blocks-engine-choice-group' => 'true',
+ 'data-blocks-engine-choice-config' => $config,
+ ), static fn(string $value): bool => '' !== $value),
+ )));
+ if (isset($attrs['anchor'])) $groupAttrs['anchor'] = $attrs['anchor'];
+ if (isset($attrs['className'])) $groupAttrs['className'] = $attrs['className'];
+ $groupOpening = '';
+ $innerContent = array($groupOpening);
foreach ($children as $_) $innerContent[] = null;
- $innerContent[] = '' . $tagName . '>';
+ $innerContent[] = '
';
return array(
- 'blockName' => $blockName,
- 'attrs' => $attrs,
+ 'blockName' => 'core/group',
+ 'attrs' => $groupAttrs,
'innerBlocks' => $children,
- 'innerHTML' => $opening . '' . $tagName . '>',
+ 'innerHTML' => $groupOpening . '',
'innerContent' => $innerContent,
);
}
diff --git a/php-transformer/src/HtmlToBlocks/Elements/WrapperCoalescer.php b/php-transformer/src/HtmlToBlocks/Elements/WrapperCoalescer.php
index 111f048d54..a545dbb75d 100644
--- a/php-transformer/src/HtmlToBlocks/Elements/WrapperCoalescer.php
+++ b/php-transformer/src/HtmlToBlocks/Elements/WrapperCoalescer.php
@@ -278,6 +278,7 @@ private function hasIndependentWrapperOwnership(array $block): bool
// A dialog Group's identity includes its runtime shell and bindings.
return !empty($attrs['metadata']['blocksEngineRuntimeAttributes'])
|| isset($attrs['metadata']['blocksEngineDialog'])
+ || isset($attrs['metadata']['blocksEngineChoiceGroup'])
|| !empty($block['_editability_runtime_owned'])
|| !empty($block['_editability_visual_owned'])
|| !empty($attrs['backgroundColor'])
diff --git a/php-transformer/src/HtmlToBlocks/Generators/AuthoredControlState.php b/php-transformer/src/HtmlToBlocks/Generators/AuthoredControlState.php
index 25cf81f607..93b7bae74e 100644
--- a/php-transformer/src/HtmlToBlocks/Generators/AuthoredControlState.php
+++ b/php-transformer/src/HtmlToBlocks/Generators/AuthoredControlState.php
@@ -5,6 +5,7 @@
use Automattic\BlocksEngine\PhpTransformer\Contract\CaptureEvidence;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Support\NativeControlState;
+use Automattic\BlocksEngine\PhpTransformer\WordPress\AuthoredControlStateScript;
/** Shared property codec/view asset for existing authored controls, not a registry. */
final class AuthoredControlState
@@ -49,40 +50,7 @@ public static function state(string $kind, array $attrs): ?array
public static function viewScript(): string
{
- return <<<'JS'
-(function(){
- var key=Symbol.for('blocks-engine/authored-control-state/v1');
- if(window[key]){window[key]();return;}
- var mounted=new WeakSet();
- function keys(state,names){return state&&typeof state==='object'&&!Array.isArray(state)&&Object.keys(state).length===names.length&&names.every(function(name){return Object.prototype.hasOwnProperty.call(state,name);});}
- function mount(){
- var inputs=[];
- document.querySelectorAll('input[data-blocks-engine-control-state],select[data-blocks-engine-control-state],textarea[data-blocks-engine-control-state]').forEach(function(control){
- if(mounted.has(control))return;
- var state;try{state=JSON.parse(control.getAttribute('data-blocks-engine-control-state'));}catch(error){return;}
- if(!state||state.version!==1)return;
- if(control instanceof HTMLInputElement&&control.type!=='file'&&state.kind==='input'&&state.type===control.type&&keys(state,['version','kind','type','value','defaultValue','checked','defaultChecked','indeterminate'])&&typeof state.value==='string'&&typeof state.defaultValue==='string'&&typeof state.checked==='boolean'&&typeof state.defaultChecked==='boolean'&&typeof state.indeterminate==='boolean'){
- if(control.defaultValue!==state.defaultValue)control.defaultValue=state.defaultValue;
- if(control.defaultChecked!==state.defaultChecked)control.defaultChecked=state.defaultChecked;
- if(control.value!==state.value)control.value=state.value;
- inputs.push({control:control,state:state});
- }else if(control instanceof HTMLTextAreaElement&&state.kind==='textarea'&&keys(state,['version','kind','value','defaultValue'])&&typeof state.value==='string'&&typeof state.defaultValue==='string'){
- if(control.defaultValue!==state.defaultValue)control.defaultValue=state.defaultValue;
- control.value=state.value;
- }else if(control instanceof HTMLSelectElement&&state.kind==='select'&&keys(state,['version','kind','options'])&&Array.isArray(state.options)&&state.options.length===control.options.length&&state.options.every(function(option){return keys(option,['selected','defaultSelected'])&&typeof option.selected==='boolean'&&typeof option.defaultSelected==='boolean';})&&(control.multiple||state.options.filter(function(option){return option.selected;}).length<=1)){
- state.options.forEach(function(option,index){if(control.options[index].defaultSelected!==option.defaultSelected)control.options[index].defaultSelected=option.defaultSelected;});
- control.selectedIndex=-1;
- state.options.forEach(function(option,index){control.options[index].selected=option.selected;});
- }else if(!(control instanceof HTMLInputElement&&control.type==='file'&&state.kind==='file'&&keys(state,['version','kind'])))return;
- mounted.add(control);
- });
- inputs.forEach(function(item){item.control.checked=false;});
- inputs.forEach(function(item){item.control.checked=item.state.checked;item.control.indeterminate=item.state.indeterminate;});
- }
- window[key]=mount;
- if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount,{once:true});else mount();
-})();
-JS;
+ return AuthoredControlStateScript::viewScript();
}
/** Shared serialization helper in the three registered editors. */
diff --git a/php-transformer/src/HtmlToBlocks/Generators/CapturedChoiceGroupBlockGenerator.php b/php-transformer/src/HtmlToBlocks/Generators/CapturedChoiceGroupBlockGenerator.php
index d673403b6a..6aff8295b3 100644
--- a/php-transformer/src/HtmlToBlocks/Generators/CapturedChoiceGroupBlockGenerator.php
+++ b/php-transformer/src/HtmlToBlocks/Generators/CapturedChoiceGroupBlockGenerator.php
@@ -3,6 +3,8 @@
namespace Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Generators;
+use Automattic\BlocksEngine\PhpTransformer\WordPress\CapturedChoiceGroupScript;
+
/** Defines the editable companion block for captured choice transitions. */
final class CapturedChoiceGroupBlockGenerator
{
@@ -36,103 +38,7 @@ public function definition(string $blockName): array
} );
} )( window.wp.blocks, window.wp.blockEditor, window.wp.element );
JS;
- $view = <<<'JS'
-( function() {
- function config( element ) {
- try { return JSON.parse( element.getAttribute( 'data-blocks-engine-choice-config' ) || '{}' ); } catch ( error ) { return null; }
- }
- function choices( element ) {
- return Array.prototype.slice.call( element.querySelectorAll( 'button,[role="radio"],[role="option"],[role="tab"],input[type="radio"],input[type="checkbox"]' ) );
- }
- function applyBindings( element, state ) {
- ( state.bindings || [] ).forEach( function( binding ) {
- var choice = choices( element )[ binding.choiceIndex ];
- if ( ! choice ) return;
- ( binding.nodes || [] ).forEach( function( nodeBinding ) {
- var node = choice;
- ( nodeBinding.path || [] ).forEach( function( childIndex ) {
- var children = Array.prototype.filter.call( node.children || [], function() { return true; } );
- node = children[ childIndex ] || null;
- } );
- if ( ! node ) return;
- Object.keys( nodeBinding.attributes || {} ).forEach( function( name ) {
- var value = nodeBinding.attributes[ name ];
- if ( value === null ) node.removeAttribute( name );
- else node.setAttribute( name, String( value ) );
- } );
- } );
- } );
- }
- function setSelection( element, state, data ) {
- var nodes = choices( element );
- nodes.forEach( function( node, index ) {
- node.setAttribute( 'data-blocks-engine-choice-index', String( index ) );
- if ( ! state ) return;
- node.setAttribute( 'data-blocks-engine-choice-active', index === state.selectedIndex ? 'true' : 'false' );
- if ( node.getAttribute( 'aria-pressed' ) !== null ) node.setAttribute( 'aria-pressed', index === state.selectedIndex ? 'true' : 'false' );
- } );
- if ( ! state ) {
- element.removeAttribute( 'data-blocks-engine-choice-selection' );
- element.removeAttribute( 'data-blocks-engine-choice-selected-index' );
- return;
- }
- element.setAttribute( 'data-blocks-engine-choice-selected-index', String( state.selectedIndex ) );
- var choice = ( data.choices || [] )[ state.selectedIndex ] || {};
- element.setAttribute( 'data-blocks-engine-choice-selection', JSON.stringify( { observed_choice_key: choice.observed_choice_key || ( 'choice-' + state.selectedIndex ), source_value: Object.prototype.hasOwnProperty.call( choice, 'source_value' ) ? choice.source_value : null, selected_index: state.selectedIndex } ) );
- }
- function mount( element ) {
- if ( element.dataset.blocksEngineChoiceMounted ) return;
- var data = config( element );
- if ( ! data || ! Array.isArray( data.states ) || ! data.states.length ) return;
- element.dataset.blocksEngineChoiceMounted = 'true';
- var states = {};
- data.states.forEach( function( state ) { states[ String( state.selectedIndex ) ] = state; } );
- var current = null;
- function apply( index, focus ) {
- var state = states[ String( index ) ];
- if ( ! state ) return;
- applyBindings( element, state );
- // Bindings set attributes (default state); the captured selection
- // owns each native checkable's current state.
- choices( element ).forEach( function( node, index ) {
- if ( node instanceof HTMLInputElement && ( node.type === 'checkbox' || node.type === 'radio' )
- && Array.isArray( state.selected ) && typeof state.selected[ index ] === 'boolean' ) node.checked = state.selected[ index ];
- } );
- current = state;
- setSelection( element, state, data );
- if ( focus ) {
- var node = choices( element )[ index ];
- if ( node && node.focus ) node.focus();
- }
- }
- setSelection( element, current, data );
- element.addEventListener( 'click', function( event ) {
- var node = event.target && event.target.closest ? event.target.closest( '[data-blocks-engine-choice-index]' ) : null;
- if ( node && element.contains( node ) ) {
- var index = Number( node.getAttribute( 'data-blocks-engine-choice-index' ) );
- if ( Number.isInteger( index ) ) apply( index, false );
- }
- } );
- element.addEventListener( 'keydown', function( event ) {
- var node = event.target && event.target.closest ? event.target.closest( '[data-blocks-engine-choice-index]' ) : null;
- if ( ! node || ! element.contains( node ) ) return;
- var index = Number( node.getAttribute( 'data-blocks-engine-choice-index' ) );
- var count = choices( element ).length;
- if ( ! Number.isInteger( index ) || ! count ) return;
- var next = index;
- if ( event.key === 'ArrowRight' || event.key === 'ArrowDown' ) next = ( index + 1 ) % count;
- else if ( event.key === 'ArrowLeft' || event.key === 'ArrowUp' ) next = ( index - 1 + count ) % count;
- else if ( event.key === 'Home' ) next = 0;
- else if ( event.key === 'End' ) next = count - 1;
- else return;
- event.preventDefault();
- apply( next, true );
- } );
- }
- function mountAll() { document.querySelectorAll( '[data-blocks-engine-choice-group="true"]' ).forEach( mount ); }
- if ( 'loading' === document.readyState ) document.addEventListener( 'DOMContentLoaded', mountAll ); else mountAll();
-} )();
-JS;
+
return array(
'name' => self::LOCAL_NAME,
@@ -150,7 +56,7 @@ function mountAll() { document.querySelectorAll( '[data-blocks-engine-choice-gro
'assets' => array(
'index.js' => str_replace(array('__BLOCK_NAME__', '__ATTRIBUTES__'), array($blockName, json_encode($attributes, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES)), $editor),
),
- 'view_js' => AuthoredControlState::viewScript() . "\n" . $view,
+ 'view_js' => AuthoredControlState::viewScript() . "\n" . CapturedChoiceGroupScript::viewScript(),
'script_dependencies' => array('index.js' => array('wp-blocks', 'wp-block-editor', 'wp-element')),
);
}
diff --git a/php-transformer/src/WordPress/AuthoredControlStateScript.php b/php-transformer/src/WordPress/AuthoredControlStateScript.php
new file mode 100644
index 0000000000..0a72715cfa
--- /dev/null
+++ b/php-transformer/src/WordPress/AuthoredControlStateScript.php
@@ -0,0 +1,46 @@
+]*>(.*)<\/div>$/s', trim( $content ), $match ) ) return $content;
+ $opening = '<' . $shell['tagName'];
+ foreach ( $shell['attributes'] ?? array() as $name => $value ) {
+ if ( ! in_array( $name, array( 'id', 'class', 'aria-label', 'data-blocks-engine-choice-group', 'data-blocks-engine-choice-config' ), true ) || ! is_string( $value ) ) continue;
+ $opening .= ' ' . $name . '="' . esc_attr( $value ) . '"';
+ }
+ return $opening . '>' . $match[1] . '' . $shell['tagName'] . '>';
+}, 20, 2 );
+PHP
+ . "\nadd_action( 'wp_enqueue_scripts', static function (): void { wp_register_script( 'blocks-engine-choice-groups', false, array(), null, true ); wp_enqueue_script( 'blocks-engine-choice-groups' ); wp_add_inline_script( 'blocks-engine-choice-groups', " . var_export($script, true) . " ); } );";
+ }
+}
diff --git a/php-transformer/src/WordPressSitePlan/ThemeBootstrap.php b/php-transformer/src/WordPressSitePlan/ThemeBootstrap.php
index 15795685fc..abfd749783 100644
--- a/php-transformer/src/WordPressSitePlan/ThemeBootstrap.php
+++ b/php-transformer/src/WordPressSitePlan/ThemeBootstrap.php
@@ -502,6 +502,9 @@ public static function functionsPhp(array $assets, array $scripts = array(), arr
$entranceScript = \Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Generators\ViewportEntranceRuntime::script('__BLOCKS_ENGINE_VIEWPORT_QUERIES__');
$lines[] = "add_action( 'wp_enqueue_scripts', static function (): void { \$queries = array(); if ( method_exists( 'WP_Theme_JSON', 'get_viewport_media_queries' ) ) { foreach ( WP_Theme_JSON::get_viewport_media_queries( wp_get_global_settings( array( 'viewport' ) ), array( 'include_desktop' => true ) ) as \$state => \$query ) { \$queries[ ltrim( \$state, '@' ) ] = preg_replace( '/^@media\\s+/', '', \$query ); } } wp_register_script( 'blocks-engine-viewport-entrances', false, array(), null, true ); wp_enqueue_script( 'blocks-engine-viewport-entrances' ); wp_add_inline_script( 'blocks-engine-viewport-entrances', str_replace( '__BLOCKS_ENGINE_VIEWPORT_QUERIES__', (string) wp_json_encode( (object) \$queries ), " . var_export($entranceScript, true) . " ) ); } );";
}
+ if (self::markupContains($documents, 'blocksEngineChoiceGroup')) {
+ $lines[] = CapturedChoiceGroupRuntime::bootstrap();
+ }
if (self::markupContains($documents, 'blocksEngineDialog')) {
$lines[] = CapturedDialogRuntime::bootstrap();
}
diff --git a/php-transformer/tests/contract/run.php b/php-transformer/tests/contract/run.php
index eb6eab0913..f956819468 100644
--- a/php-transformer/tests/contract/run.php
+++ b/php-transformer/tests/contract/run.php
@@ -6503,10 +6503,10 @@ public function recognize(DOMElement $element, PatternContext $context): ?Patter
);
$choiceGroupArtifact = $compiler->compile($choiceGroupInput)->toArray();
$choiceMarkup = (string) ($choiceGroupArtifact['serialized_blocks'] ?? '');
-$choiceConfig = (string) (($choiceGroupArtifact['source_reports']['companion_plugin_payload']['blocks'][0]['view_js'] ?? ''));
+$choiceConfig = \Automattic\BlocksEngine\PhpTransformer\WordPressSitePlan\CapturedChoiceGroupRuntime::bootstrap();
$choiceForms = array_values(array_filter($choiceGroupArtifact['source_reports']['artifact']['runtime_declarations'] ?? array(), static fn(array $declaration): bool => 'entity_collection' === ($declaration['kind'] ?? '') && 'forms' === ($declaration['type'] ?? '')));
$assert(1 === ($choiceGroupArtifact['source_reports']['captured_interactions']['projected_choice_group_count'] ?? null), 'captured choice groups report one projected group');
-$assert(str_contains($choiceMarkup, 'captured-choice-group-site/captured-choice-group'), 'captured choice groups serialize as an owned companion block');
+$assert(! str_contains($choiceMarkup, 'captured-choice-group-site/captured-choice-group') && str_contains($choiceMarkup, 'blocksEngineChoiceGroup'), 'captured choice groups serialize as core Groups with captured behavior');
$assert(str_contains($choiceMarkup, 'One') && str_contains($choiceMarkup, 'Two'), 'choice group inner content remains in the editable block tree');
$assert(str_contains($choiceConfig, 'observed_choice_key') && str_contains($choiceConfig, 'source_value'), 'choice behavior carries observed identity without treating it as a source scalar');
$assert(str_contains($choiceConfig, 'bindings') && str_contains($choiceConfig, 'selectedIndex'), 'choice behavior carries bounded state bindings without replaying captured HTML');
diff --git a/php-transformer/tests/unit/captured-choice-group-inline-runtime.php b/php-transformer/tests/unit/captured-choice-group-inline-runtime.php
index df9b2f6855..8981ac48b4 100644
--- a/php-transformer/tests/unit/captured-choice-group-inline-runtime.php
+++ b/php-transformer/tests/unit/captured-choice-group-inline-runtime.php
@@ -47,19 +47,29 @@
$result = $compile($page(array(array('transitions' => $transitions))));
$markup = (string) ($result['serialized_blocks'] ?? '');
$companion = array_values(array_filter($result['source_reports']['companion_plugin_payload']['blocks'] ?? array(), static fn(array $block): bool => 'captured-choice-group' === ($block['name'] ?? null)));
-$viewJs = (string) ($companion[0]['view_js'] ?? '');
+$writes = array_column($result['source_reports']['wordpress_site_plan']['writes'] ?? array(), null, 'target_path');
+$viewJs = (string) ($writes['functions.php']['payload']['data'] ?? '');
$config = array();
-if (1 === preg_match('/data-blocks-engine-choice-config="([^"]*)"/', $markup, $match)) {
- $config = json_decode(html_entity_decode($match[1], ENT_QUOTES), true) ?: array();
+$shell = null;
+preg_match_all('//', $markup, $groups);
+foreach ($groups[1] as $json) {
+ $attrs = json_decode($json, true);
+ if (isset($attrs['metadata']['blocksEngineChoiceGroup'])) {
+ $shell = $attrs['metadata']['blocksEngineChoiceGroup'];
+ $config = json_decode($shell['attributes']['data-blocks-engine-choice-config'], true);
+ }
}
$diagnostics = (string) json_encode($result['source_reports'] ?? array());
$assert(1 === ($result['source_reports']['captured_interactions']['projected_choice_group_count'] ?? null), 'the inline choice group is projected');
-$assert(str_contains($markup, 'inline-choice-site/captured-choice-group'), 'the inline choice group materializes as the captured choice-group companion');
+$assert(! str_contains($markup, 'inline-choice-site/captured-choice-group') && null !== $shell && array() === $companion, 'the inline choice group is a core Group with captured behavior, not a companion block');
+$assert(str_contains($markup, 'class="wp-block-group sizes"'), 'the saved container uses canonical core Group markup');
+$assert('Size' === ($shell['attributes']['aria-label'] ?? null), 'the core Group retains the authored accessible label in its runtime shell');
+$assert(1 === substr_count($viewJs, "add_filter( 'render_block_core/group'"), 'the public site plan installs one shared choice shell renderer');
$assert(! str_contains($markup, 'wp:html') && ! str_contains($markup, 'core/html'), 'the inline choice group is not frozen as raw HTML');
$assert(4 === substr_count($markup, '