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 @@ -358,19 +358,25 @@ public function textarea(DOMElement $textarea, ?DOMElement $label = null, bool $
}

/**
* Return a compact native button on the same terms as `input()`: a submit
* (or other form-action) control the source styles has no readable prose
* equivalent, because a Gutenberg button saves as an anchor and cannot
* submit its ancestor form.
* Return an editable native form action. Plain labels use core/button's
* native button tag; controls needing unsupported attributes or their
* original containing block retain the authored representation.
*
* @return array<string, mixed>|null
*/
public function button(DOMElement $button, bool $forceNative = false): ?array
public function button(DOMElement $button, bool $forceNative = false, bool $preserveContainingBlock = false): ?array
{
if ( ! $forceNative && array() === ($this->authoredPresentationDeclarations)($button) ) {
return null;
}

// Core/button supports native form actions. Plain labels do not need
// a companion merely because their source has authored presentation.
// Let the normal source projection own the wrapper/control selectors.
if (!$preserveContainingBlock && $this->hasPlainCoreButtonLabel($button)) {
return $this->plainCoreButton($button);
}

$this->session->authorSelectorProjectionState()->recordAuthoredControlCandidate($button);
$generator = new AuthoredButtonBlockGenerator();
$registry = $this->session->requireGeneratedBlockRegistry();
Expand Down Expand Up @@ -434,6 +440,10 @@ public function runtimeButton(DOMElement $element): array
/** @return array<string, mixed> */
private function runtimeButtonBlock(DOMElement $button): array
{
if ($this->hasPlainCoreButtonLabel($button)) {
return $this->plainCoreButton($button);
}

// SVG controls have no RichText label. Model their artwork as core
// images and containers rather than an opaque contentParts tree.
// Inline-only icons and CSS-painted controls still use the native
Expand All @@ -454,6 +464,48 @@ private function runtimeButtonBlock(DOMElement $button): array
return BlockFactory::leaf($registry->blockName(AuthoredButtonBlockGenerator::LOCAL_NAME), $attrs, $markup);
}

private function hasPlainCoreButtonLabel(DOMElement $button): bool
{
if ('button' !== strtolower($button->tagName) || '' === trim($button->textContent) || SourceDom::childElementCount($button) > 0) return false;
// Bound controls and provider form actions keep their existing owning
// pipeline. Captured native forms, however, already retain their fields
// and need an editable, source-shaped action, like captured choices.
foreach ($button->attributes as $attribute) {
if (!in_array(strtolower($attribute->nodeName), array('type', 'class', 'style', CaptureEvidence::CHOICE_INDEX), true)) return false;
}
for ($ancestor = $button->parentNode; $ancestor instanceof DOMElement; $ancestor = $ancestor->parentNode) {
if ('form' === strtolower($ancestor->tagName)) {
foreach ($ancestor->getElementsByTagName('*') as $field) {
if ($field->hasAttribute(CaptureEvidence::NATIVE_CONTROL_STATE)) return true;
}
return false;
}
}
return $button->hasAttribute(CaptureEvidence::CHOICE_INDEX);
}

private function plainCoreButton(DOMElement $button): array
{
// Keep source selectors on the native control, not on synthetic button
// wrappers. The inner button is an editor-only RichText carrier.
$this->session->authorSelectorProjectionState()->recordAuthoredControlCandidate($button);
$this->session->authorSelectorProjectionState()->markRetainedSourcePath($button->getNodePath() ?? '');
$attributes = array();
foreach ($button->attributes as $attribute) {
$attributes[strtolower($attribute->nodeName)] = $attribute->nodeValue ?? '';
}
if (!isset($attributes['type'])) $attributes['type'] = 'submit';
$label = $this->createBlock->createBlock('core/button', array(
'tagName' => 'button',
'type' => $attributes['type'],
'text' => $this->runtime->escapeHtml($button->textContent),
), array());
return $this->createBlock->createBlock('core/group', array(
'tagName' => 'div',
'metadata' => array('blocksEngineControlBox' => $attributes, 'blocksEngineControlTagName' => 'button', 'blocksEngineControlLabel' => true),
), array($label), $button);
}

private function isCssDrawnControl(DOMElement $element): bool
{
if ('svg' === strtolower($element->tagName)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ public function convert(DOMElement $element, string $tagName, array &$fallbacks,
return ConversionOutcome::handled($this->context->convertButton($element));
}

// A photo control is a native container around editable core images,
// not an opaque authored-button contentParts tree. Keep the button's
// containing block so percentage-sized thumbnails retain their geometry.
if ( ( $this->hasFluidContentImage($element) || $this->hasContentScaleImage($element) ) && '' === trim($element->textContent) ) {
$container = $this->context->convertButtonWrapperGroup($element, $fallbacks);
if ( null !== $container ) return ConversionOutcome::handled($container);
}

if ( $this->context->isRuntimeDomTarget($element) && ( array() !== AuthoredButtonBlockGenerator::sourceSafeAttributes($element) || ! $this->sourceElementClassifier->isRichTextButtonLabel($element) ) ) {
$runtimeButton = $this->context->runtimeButton($element);
if ( null !== $runtimeButton ) {
Expand Down Expand Up @@ -126,6 +134,20 @@ private function hasContentScaleImage(DOMElement $element): bool
return false;
}

private function hasFluidContentImage(DOMElement $element): bool
{
foreach ($element->getElementsByTagName('img') as $image) {
$size = $this->context->imageMinimumPixelSize($image);
if (null === $size || (null === $size['width'] && null === $size['height'])) {
foreach (array('width', 'height') as $axis) {
$intrinsic = SourceDom::attr($image, $axis);
if (is_numeric($intrinsic) && (float) $intrinsic > self::ICON_SCALE_MAX_PX) return true;
}
}
}
return false;
}

private function hasAccessibleIconOnlyContent(DOMElement $element): bool
{
if ( '' === trim(SourceDom::attr($element, 'aria-label')) ) {
Expand Down
15 changes: 14 additions & 1 deletion php-transformer/src/HtmlToBlocks/HtmlCompilation.php
Original file line number Diff line number Diff line change
Expand Up @@ -1924,7 +1924,7 @@ public function percentageSizedFormButton(DOMElement $button): ?array
return null;
}
$this->session->authorSelectorProjectionState()->markRetainedSourcePath($button->getNodePath() ?? '');
return $this->authoredFormControlBlockConverter->button($button, true);
return $this->authoredFormControlBlockConverter->button($button, true, true);
}

/** Keep containing-block-relative sizes on the original, editable control. */
Expand Down Expand Up @@ -2248,6 +2248,19 @@ public function convertButtonWrapperGroup(DOMElement $button, array &$fallbacks)
return null;
}

if ( '' === trim($button->textContent) && $button->getElementsByTagName('img')->length > 0 ) {
$attributes = array();
foreach ($button->attributes as $attribute) {
$attributes[strtolower($attribute->nodeName)] = $attribute->nodeValue ?? '';
}
if (!isset($attributes['type'])) $attributes['type'] = 'submit';
return $this->createBlock('core/group', array(
'tagName' => 'button',
'className' => SourceDom::attr($button, 'class'),
'metadata' => array('blocksEngineControlBox' => $attributes, 'blocksEngineControlTagName' => 'button'),
), $children, $button);
}

return $this->layoutShells->blockForElements(array($button), $children, $button);
}

Expand Down
7 changes: 4 additions & 3 deletions php-transformer/src/HtmlToBlocks/Style/EngineSupportCss.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,9 +366,10 @@ public function beforeAuthorCss(string $serializedBlocks): array
}
foreach ( array( 'inline-block', 'block', 'flex', 'inline-flex', 'inline-grid', 'inline-table' ) as $display ) {
$modifier = $neutralButton . '-display-' . $display;
if ( str_contains($serializedBlocks, $modifier) ) {
$buttonCss .= ':where(.' . $neutralButton . '.' . $modifier . ')>.wp-block-button__link{display:' . $display . '!important}';
}
// Support sheets from multiple routes can coexist. Always emit
// every modifier, or a later route's generic inline reset can
// override an earlier route's source display restoration.
$buttonCss .= ':where(.' . $neutralButton . '.' . $modifier . ')>.wp-block-button__link{display:' . $display . '!important}';
}
$parts[] = $buttonCss;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,38 @@ public static function source(): string
{
return str_replace(array('__DEVICE_INLINE__', '__DEVICE_CLASS__', '__VIEWPORT_ENTRANCE__', '__RESPONSIVE_FRAGMENT__'), array(CaptureEvidence::DEVICE_INLINE, CaptureEvidence::DEVICE_CLASS, CaptureEvidence::VIEWPORT_ENTRANCE, CaptureEvidence::RESPONSIVE_FRAGMENT), <<<'PHP'
add_filter( 'render_block', static function ( string $content, array $block ): string {
// RichText stays editable without introducing a published label box.
if ( 'core/paragraph' === ( $block['blockName'] ?? '' ) && ! empty( $block['attrs']['metadata']['blocksEngineControlLabel'] ) ) {
return preg_replace( '/^<p\b[^>]*>(.*)<\/p>\s*$/s', '$1', trim( $content ) );
}
// Core containers own CSS-drawn control boxes in the editor. On the
// front end keep their authored box attributes, not group layout chrome.
$box = $block['attrs']['metadata']['blocksEngineControlBox'] ?? null;
if ( 'core/group' === ( $block['blockName'] ?? '' ) && is_array( $box ) ) {
$processor = new WP_HTML_Tag_Processor( $content );
if ( $processor->next_tag() ) {
// Keep projection identities: route CSS can address these markers
// even though the published box sheds Core's group chrome.
$classes = preg_split( '/\s+/', (string) $processor->get_attribute( 'class' ) );
$markers = array_filter( $classes, static fn ( string $class ): bool => str_starts_with( $class, 'blocks-engine-' ) );
$box['class'] = trim( ( $box['class'] ?? '' ) . ' ' . implode( ' ', $markers ) );
$processor->remove_attribute( 'class' );
$processor->remove_attribute( 'style' );
foreach ( $box as $name => $value ) {
if ( is_string( $name ) && is_string( $value ) && preg_match( '/^(?:class|style|id|type|name|title|tabindex|disabled|hidden|role|data-(?!wp-)[a-z0-9_.:-]+|aria-[a-z-]+)$/D', $name ) ) $processor->set_attribute( $name, $value );
}
return $processor->get_updated_html();
$content = $processor->get_updated_html();
if ( ! empty( $block['attrs']['metadata']['blocksEngineControlLabel'] ) ) {
// The nested Core button is an editor-only RichText surface.
$content = preg_replace( '/(<div\b[^>]*>)\s*<div\b[^>]*>\s*<button\b[^>]*>([\s\S]*)<\/button>\s*<\/div>\s*(<\/div>\s*)$/', '$1$2$3', $content, 1 );
}
if ( 'button' === ( $block['attrs']['metadata']['blocksEngineControlTagName'] ?? null ) ) {
// Core's editor keeps a selectable group; the published control
// must remain a native button, without an extra containing box.
$content = preg_replace( '/^<div\b/', '<button', $content, 1 );
$content = preg_replace( '/<\/div>\s*$/', '</button>', $content, 1 );
}
return $content;
}
}
$attributes = $block['attrs']['metadata']['blocksEngineRuntimeAttributes'] ?? null;
Expand Down
2 changes: 1 addition & 1 deletion php-transformer/src/WordPressSitePlan/ThemeBootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ public static function functionsPhp(array $assets, array $scripts = array(), arr
$breadcrumbLabels = BreadcrumbLabelRuntime::labels($documents, $pages);
$breadcrumbPostTrails = BreadcrumbLabelRuntime::postTrails($pages);
if (array() !== $breadcrumbLabels || array() !== $breadcrumbPostTrails) $lines[] = BreadcrumbLabelRuntime::source($breadcrumbLabels, $breadcrumbPostTrails);
if (self::markupContains($documentsWithMenus, 'blocksEngineRuntimeAttributes')) {
if (self::markupContains($documentsWithMenus, 'blocksEngineRuntimeAttributes') || self::markupContains($documentsWithMenus, 'blocksEngineControlBox')) {
$lines[] = RuntimeAttributesRuntime::source();
}
foreach (EditorRestingStateRuntime::MARKERS as $marker) {
Expand Down
24 changes: 24 additions & 0 deletions php-transformer/tests/unit/button-shared-display.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\HtmlTransformer;

// Shared support styles from another route must not undo the first route's
// source display, after neutralizing core/button's synthetic wrappers.
$pages = array(
'<style>.action{display:inline-flex;padding:14px 26px;background:red}</style><div><a class="action" href="/book">Book a fitment</a></div>',
(string) file_get_contents(dirname(__DIR__) . '/fixtures/button-intrinsic-height.html'),
);
foreach ($pages as $html) {
$result = (new HtmlTransformer())->transform($html)->toArray();
$css = implode('', array_column(array_filter($result['assets'], static fn(array $a): bool => 'css' === ($a['kind'] ?? '')), 'content'));
$restore = ':where(.blocks-engine-layout-child-button.blocks-engine-layout-child-button-display-inline-flex)>.wp-block-button__link{display:inline-flex!important}';
if (!str_contains($css, $restore)) {
throw new RuntimeException('Every route support sheet must restore inline-flex source buttons');
}
if (strpos($css, $restore) < strpos($css, 'display:inline!important')) {
throw new RuntimeException('Source display restoration must follow the generic inline reset');
}
}
echo "Shared button source display: passed\n";
39 changes: 39 additions & 0 deletions php-transformer/tests/unit/native-button-ownership.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);

require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\HtmlTransformer;

// Core lowering must not steal the native form or runtime-binding owners.
$cases = array(
'<form><input name="email"><button type="submit" class="action">Send</button></form>' => '<button type="submit" class="action">Send</button>',
'<button type="button" aria-controls="panel" data-action="open">Open</button>' => 'aria-controls="panel"',
);
foreach ($cases as $source => $nativeMarkup) {
$result = (new HtmlTransformer())->transform('<style>.action{padding:12px;background:#123}</style>' . $source)->toArray();
$markup = $result['serialized_blocks'];
if (!str_contains($markup, $nativeMarkup) || str_contains($markup, 'blocksEngineControlLabel')) {
throw new RuntimeException('Native control ownership was bypassed: ' . $markup);
}
}
// Captured native forms own their controls too, but their plain actions
// must expose editable Core labels while keeping the original native box.
foreach (array('button', 'reset', 'submit') as $type) {
$result = (new HtmlTransformer())->transform(
'<style>.action{padding:8px;background:#123;color:white}</style>'
. '<form><input name="email" data-blocks-engine-capture-native-control-state=\'{"version":1,"kind":"input","value":"","defaultValue":""}\'>'
. '<button type="' . $type . '" class="action">Choose &amp; continue</button></form>'
)->toArray();
$markup = $result['serialized_blocks'];
if (str_contains($markup, '/authored-button')
|| !str_contains($markup, '<!-- wp:button ')
|| !str_contains($markup, '"blocksEngineControlBox":{"type":"' . $type . '","class":"action"}')
|| !str_contains($markup, '"blocksEngineControlTagName":"button"')
|| !str_contains($markup, '<button type="' . $type . '"')
|| !str_contains($markup, 'Choose &amp; continue')
|| 'pass' !== ($result['source_reports']['wp_block_validity']['status'] ?? null)) {
throw new RuntimeException('Captured form action must retain its native box and editable Core label: ' . $markup);
}
}
echo "Native button ownership: passed\n";
24 changes: 24 additions & 0 deletions php-transformer/tests/unit/native-form-action-core.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);

require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\HtmlTransformer;

// Public interface: relative form actions must not acquire synthetic button
// wrappers or redirect a shared source selector onto unrelated core links.
$result = (new HtmlTransformer())->transform(
'<style>.action{width:100%;padding:12px;background:#123;color:white}</style>'
. '<form><input name="email" data-blocks-engine-capture-native-control-state=\'{"version":1,"kind":"input","value":"","defaultValue":""}\'><textarea name="message"></textarea><button type="submit" class="action">Find &amp; choose</button></form>'
. '<a class="action" href="/shop/">Shop</a>'
)->toArray();
$markup = $result['serialized_blocks'];
if (str_contains($markup, '/authored-button')
|| !str_contains($markup, '"blocksEngineControlTagName":"button"')
|| !str_contains($markup, '"blocksEngineControlBox":{"type":"submit","class":"action"}')
|| !str_contains($markup, '"blocksEngineControlLabel":true')
|| !str_contains($markup, '<button type="submit" class="wp-block-button__link wp-element-button">Find &amp; choose</button>')
|| 'pass' !== ($result['source_reports']['wp_block_validity']['status'] ?? null)) {
throw new RuntimeException('Native form action must use editable core blocks without replacing its source box: ' . $markup);
}
echo "Native form action core: passed\n";
33 changes: 33 additions & 0 deletions php-transformer/tests/unit/photo-button-core.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);

require dirname(__DIR__, 2) . '/vendor/autoload.php';

use Automattic\BlocksEngine\PhpTransformer\HtmlToBlocks\HtmlTransformer;

// Public conversion must expose the photo to Core's image editor without
// changing the native control or its percentage-sized containing block.
$result = (new HtmlTransformer())->transform(
'<style>.photo{border:1px solid #aaa}.photo img{width:100%;aspect-ratio:1;object-fit:cover}</style>'
. '<button aria-label="Product photo" class="photo"><img src="https://example.com/photo.jpg" alt="" width="256" height="256"></button>'
)->toArray();
$markup = $result['serialized_blocks'];
foreach (array(
'no opaque control' => !str_contains($markup, '/authored-button'),
'no generated shell' => !str_contains($markup, '/layout-shell'),
'editable image' => str_contains($markup, '<!-- wp:image '),
'native container' => str_contains($markup, '"blocksEngineControlTagName":"button"'),
'accessible name' => str_contains($markup, '"aria-label":"Product photo"'),
'valid core save' => 'pass' === ($result['source_reports']['wp_block_validity']['status'] ?? ''),
) as $label => $passed) {
if (!$passed) throw new RuntimeException($label . ': ' . $markup);
}
// A small named icon is not photo content: retain the icon control's
// native authored representation, including its accessibility attributes.
$icon = (new HtmlTransformer())->transform(
'<button type="button" aria-label="Choose photo"><img src="https://example.com/icon.jpg" alt="" width="24" height="24"></button>'
)->toArray()['serialized_blocks'];
if (!str_contains($icon, '/authored-button') || !str_contains($icon, 'aria-label="Choose photo"')) {
throw new RuntimeException('Small icons must keep native control lowering: ' . $icon);
}
echo "Photo button core: 8 assertions passed\n";
Loading
Loading