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 @@ -5,7 +5,6 @@

use Automattic\BlocksEngine\PhpTransformer\Support\HtmlSerialization;
use Automattic\BlocksEngine\PhpTransformer\Contract\CaptureEvidence;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Generators\CapturedChoiceGroupBlockGenerator;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Generators\AuthoredControlState;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Patterns\PatternTreeConverter;
use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\Support\NativeControlState;
Expand All @@ -15,9 +14,8 @@
use DOMElement;
use DOMDocument;
use DOMXPath;
use LogicException;

/** Materializes captured choice evidence as an editable companion container. */
/** Materializes captured choice evidence as an editable core container. */
final class CapturedChoiceGroupConverter implements ElementConverter
{
/** Mirrors the runtime's `choices()` query so source and rendered indexes agree. */
Expand Down Expand Up @@ -52,11 +50,6 @@ public function convert(DOMElement $element, string $tagName, array &$fallbacks,
/** @param array<int, array<string, mixed>> $fallbacks @return array<string, mixed> */
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']) {
Expand Down Expand Up @@ -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 = '<div' . (isset($attrs['anchor']) ? ' id="' . $escape($attrs['anchor']) . '"' : '')
. ' class="wp-block-group' . (isset($attrs['className']) ? ' ' . $escape($attrs['className']) : '') . '">';
$innerContent = array($groupOpening);
foreach ($children as $_) $innerContent[] = null;
$innerContent[] = '</' . $tagName . '>';
$innerContent[] = '</div>';

return array(
'blockName' => $blockName,
'attrs' => $attrs,
'blockName' => 'core/group',
'attrs' => $groupAttrs,
'innerBlocks' => $children,
'innerHTML' => $opening . '</' . $tagName . '>',
'innerHTML' => $groupOpening . '</div>',
'innerContent' => $innerContent,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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,
Expand All @@ -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')),
);
}
Expand Down
46 changes: 46 additions & 0 deletions php-transformer/src/WordPress/AuthoredControlStateScript.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);

namespace Automattic\BlocksEngine\PhpTransformer\WordPress;

/** Restores captured native control properties independently of block conversion. */
final class AuthoredControlStateScript
{
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;
}
}
Loading
Loading