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
26 changes: 19 additions & 7 deletions php-transformer/docs/contracts/box-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Write one `box-tree/<route>.json` artifact file for each captured route. Set
SHA-256 of its final UTF-8 bytes (including node attributes). Declare large
sidecars in the artifact `reports` list to use capture-report byte budgets.
The reader also applies a hard 32 MiB decoded sidecar limit, 100,000 nodes,
2–8 viewports, viewport dimensions of 1–32,768 CSS pixels, geometry bounded
1–8 viewports, viewport dimensions of 1–32,768 CSS pixels, geometry bounded
by 100,000,000 CSS pixels, and 4,096 bytes per used style string.

Every element, including `html`, `head` and non-rendering elements, must carry
Expand All @@ -23,7 +23,7 @@ all observations. Do not regenerate IDs after resizing; a genuinely different
DOM needs its own document/hash. Include zero-sized boxes for non-rendering
elements. No IDs are synthesized by the transformer.

The sidecar has `viewports` keyed by name (required: `desktop`, `mobile`), each
The sidecar has `viewports` keyed by the names served by that document, each
with integer `width` and `height`, and `nodes` keyed by node ID. Each node has:

- `children`: immediate element child IDs in DOM order (no text/comment IDs);
Expand All @@ -35,6 +35,11 @@ Use computed/used values, not authored declarations; explicit strings such as
`none`, `normal`, `auto` and `0px` are significant. Physical longhands cover
padding, margin, border and overflow; the schema lists flex/grid container and
item properties, paint/compositing properties, and sizing min/max values.
Background and mask evidence uses `background-color`, `background-image`,
`mask-image`, and `mask-mode`, not the `background` or `mask` shorthands; there
are no shorthand aliases. A desktop document served separately from
`html-mobile/…` needs only its desktop observation. Every declared viewport
still requires an observation on every node. Producers must update in lockstep.

## Transformer behavior

Expand Down Expand Up @@ -64,14 +69,20 @@ is not a claim that a live capture pipeline has been implemented here.

`source_reports.box_tree[route].classification` contains `counts` keyed by
`load-bearing` and `neutral`, and `nodes` keyed by source ID with `disposition`
and the deciding `criterion`. Criteria are `paints`, `multi-child-layout`,
and the deciding `criterion`. Criteria are `paints`, `clips`, `multi-child-layout`,
`containing-block`, `semantics/id/anchor`, `interaction/state`, `motion`, and
`own-sizing`; neutral nodes have `equal-child-geometry`. Precedence follows that
order. Neutrality requires one element child, no direct non-whitespace text, and
matching x/y/width/height at **every** viewport (0.01 CSS pixel tolerance).
Containing-block ownership is resolved separately at each viewport, including
transformed ancestors of fixed descendants. These are reports, not collapse
instructions; converted blocks and author styles are unchanged.
Transparent background colors (including zero-alpha rgba and color() values)
and image-free masks do not paint. Identity transforms do not paint, but still
establish containing blocks. Overflow is `clips` only when a descendant extends
past the observed box on a clipped axis. IDs alone do not preserve wrappers:
fragment hrefs, ARIA ID references, and label `for` references do. Captured
interaction targets are preserved through their node's `interaction_states`.

The v1 evidence shape additionally accepts optional used-style strings
`animation-name`, `transition-property`, and `transition-duration`. Producers
Expand All @@ -82,10 +93,11 @@ the node independently of its resting appearance. These names indicate captured
states; they do not supply state geometry or authorize restyling. Older sidecars
remain readable; omitted motion/state fields cannot prove absence of behavior.

`projection` estimates the surviving **source box** tree below body after neutral
chains collapse: maximum `depth`, surviving non-leaf `groups`, source `leaves`,
and `groups_per_leaf` (groups divided by leaves). Body, head and document metadata
are excluded. It is not an emitted-block measurement: pattern expansion and
`projection` estimates block-producing boxes below body after neutral chains
collapse (`basis: estimated-block-producing-boxes`): maximum `depth`, surviving
non-leaf `groups`, estimated block `leaves`, and `groups_per_leaf`. Inline content,
non-rendering metadata and navigation internals are excluded; a nav counts once.
Body and head are excluded. Actual converted block depth belongs to slice 3. It is not an emitted-block measurement: pattern expansion and
non-rendering source leaves can differ from WordPress blocks. Missing/rejected
evidence has empty classifications and a null projection, never an optimistic
zero-depth estimate. Live whole-site/sdnunca measurement is deferred until the
Expand Down
23 changes: 10 additions & 13 deletions php-transformer/resources/box-tree.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@
},
"viewports": {
"type": "object",
"required": [
"desktop",
"mobile"
],
"minProperties": 1,
"maxProperties": 8,
"propertyNames": {
"type": "string",
Expand Down Expand Up @@ -83,12 +80,8 @@
},
"viewports": {
"type": "object",
"minProperties": 2,
"minProperties": 1,
"maxProperties": 8,
"required": [
"desktop",
"mobile"
],
"propertyNames": {
"type": "string",
"pattern": "^[A-Za-z0-9._:-]{1,80}$"
Expand Down Expand Up @@ -171,15 +164,17 @@
"grid-row-end",
"justify-items",
"justify-self",
"background",
"background-color",
"background-image",
"border-top",
"border-right",
"border-bottom",
"border-left",
"border-radius",
"outline",
"box-shadow",
"mask",
"mask-image",
"mask-mode",
"filter",
"opacity",
"mix-blend-mode",
Expand Down Expand Up @@ -377,7 +372,8 @@
"minLength": 1,
"maxLength": 4096
},
"background": {
"background-image": { "type": "string", "minLength": 1, "maxLength": 4096 },
"background-color": {
"type": "string",
"minLength": 1,
"maxLength": 4096
Expand Down Expand Up @@ -417,7 +413,8 @@
"minLength": 1,
"maxLength": 4096
},
"mask": {
"mask-mode": { "type": "string", "minLength": 1, "maxLength": 4096 },
"mask-image": {
"type": "string",
"minLength": 1,
"maxLength": 4096
Expand Down
89 changes: 72 additions & 17 deletions php-transformer/src/ArtifactCompiler/BoxTreeClassifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ public static function report(string $html, array $tree): array
$elements[$id] = $element;
$parents[$id] = $element->parentNode instanceof DOMElement ? $element->parentNode->getAttribute(BoxTree::NODE_ATTRIBUTE) : null;
}
$references = array();
foreach ($elements as $element) {
$href = $element->getAttribute('href');
if (str_starts_with($href, '#')) $references[rawurldecode(substr($href, 1))] = true;
foreach (array('aria-controls', 'aria-labelledby', 'aria-describedby', 'aria-owns', 'for') as $attribute) {
foreach (preg_split('/\s+/', trim($element->getAttribute($attribute)), -1, PREG_SPLIT_NO_EMPTY) as $target) $references[$target] = true;
}
}
$containing = array();
foreach ($tree['viewports'] ?? array() as $viewport => $_) {
$absolute = $fixed = array();
Expand All @@ -40,40 +48,46 @@ public static function report(string $html, array $tree): array
$counts = array('load-bearing' => 0, 'neutral' => 0);
foreach ($elements as $id => $element) {
$node = $tree['nodes'][$id];
$criterion = self::criterion($element, $node, $tree, isset($containing[$id]));
$criterion = self::criterion($element, $node, $tree, isset($containing[$id]), isset($references[$element->getAttribute('id')]));
$disposition = 'equal-child-geometry' === $criterion ? 'neutral' : 'load-bearing';
$nodes[$id] = array('disposition' => $disposition, 'criterion' => $criterion);
++$counts[$disposition];
}
// Source-box projection, not a forecast of pattern expansion in emitted blocks.
$depths = $inBody = array();
// Estimate block-producing boxes; inline content and navigation internals
// do not each become blocks. Actual emitted depth is measured in slice 3.
$depths = $inBody = $inNavigation = array();
$depth = $groups = $leaves = 0;
foreach ($elements as $id => $element) {
$inBody[$id] = 'body' === strtolower($element->tagName) || ($inBody[$parents[$id]] ?? false);
if (!$inBody[$id] || 'body' === strtolower($element->tagName)) continue;
$kept = 'load-bearing' === $nodes[$id]['disposition'];
$tag = strtolower($element->tagName);
$insideNavigation = $inNavigation[$parents[$id]] ?? false;
$inNavigation[$id] = 'nav' === $tag || $insideNavigation;
$produces = !$insideNavigation && !in_array($tag, array('span', 'a', 'strong', 'em', 'b', 'i', 'br', 'script', 'style', 'link', 'meta'), true);
$kept = $produces && 'load-bearing' === $nodes[$id]['disposition'];
$depths[$id] = ($depths[$parents[$id]] ?? 0) + ($kept ? 1 : 0);
$depth = max($depth, $depths[$id]);
if (!$tree['nodes'][$id]['children']) ++$leaves;
if ($produces && (!$tree['nodes'][$id]['children'] || 'nav' === $tag || in_array($tag, array('p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'), true))) ++$leaves;
elseif ($kept) ++$groups;
}
return array('counts' => $counts, 'nodes' => $nodes, 'projection' => $tree ? array(
'basis' => 'body-source-boxes', 'depth' => $depth, 'groups' => $groups,
'basis' => 'estimated-block-producing-boxes', 'depth' => $depth, 'groups' => $groups,
'leaves' => $leaves, 'groups_per_leaf' => $leaves ? $groups / $leaves : 0.0,
) : null);
}

private static function criterion(DOMElement $element, array $node, array $tree, bool $containing): string
private static function criterion(DOMElement $element, array $node, array $tree, bool $containing, bool $referenced): string
{
foreach ($node['viewports'] as $observation) {
$s = $observation['used_styles'];
if (self::paints($s)) return 'paints';
}
if (self::clips($node, $tree)) return 'clips';
foreach ($node['viewports'] as $observation) {
if (count($node['children']) > 1 && in_array($observation['used_styles']['display'], array('flex', 'inline-flex', 'grid', 'inline-grid'), true)) return 'multi-child-layout';
}
if ($containing) return 'containing-block';
if (!in_array(strtolower($element->tagName), array('div', 'span'), true) || $element->hasAttribute('id') || $element->hasAttribute('role') || $element->hasAttribute('name')) return 'semantics/id/anchor';
if (!in_array(strtolower($element->tagName), array('div', 'span'), true) || $referenced || $element->hasAttribute('role') || $element->hasAttribute('name')) return 'semantics/id/anchor';
foreach ($element->attributes as $attribute) {
if (str_starts_with($attribute->name, 'on') || str_starts_with($attribute->name, 'aria-') || in_array($attribute->name, array('tabindex', 'contenteditable', 'draggable', 'hidden', 'inert'), true)) return 'interaction/state';
}
Expand All @@ -96,20 +110,61 @@ private static function criterion(DOMElement $element, array $node, array $tree,
return 'equal-child-geometry';
}

/** Geometry is checked independently on each clipped axis at every captured viewport. */
private static function clips(array $node, array $tree): bool
{
foreach ($node['viewports'] as $viewport => $observation) {
$styles = $observation['used_styles'];
$clipping = array('hidden', 'clip', 'auto', 'scroll');
if (!in_array($styles['overflow-x'], $clipping, true) && !in_array($styles['overflow-y'], $clipping, true)) continue;
$box = $observation['border_box'];
$pending = $node['children'];
while ($pending) {
$descendant = $tree['nodes'][array_pop($pending)];
$child = $descendant['viewports'][$viewport]['border_box'];
foreach (array('x' => 'width', 'y' => 'height') as $axis => $size) {
$overflow = $observation['used_styles']['overflow-' . $axis];
if (in_array($overflow, $clipping, true)
&& ($child[$axis] < $box[$axis] - 0.01 || $child[$axis] + $child[$size] > $box[$axis] + $box[$size] + 0.01)) return true;
}
foreach ($descendant['children'] as $id) $pending[] = $id;
}
}
return false;
}

private static function identityTransform(string $transform): bool
{
if ('none' === $transform) return true;
if (!preg_match('/^(matrix|matrix3d)\(([^)]+)\)$/', trim($transform), $match)) return false;
$values = array_map('trim', explode(',', $match[2]));
$identity = 'matrix' === $match[1] ? array(1, 0, 0, 1, 0, 0) : array(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
if (count($values) !== count($identity)) return false;
foreach ($values as $i => $value) {
if (!is_numeric($value) || (float) $value !== (float) $identity[$i]) return false;
}
return true;
}

private static function transparent(string $color): bool
{
$color = strtolower(trim($color));
if ('transparent' === $color) return true;
if (preg_match('/\/\s*([\d.e+-]+)%?\s*\)$/', $color, $match)) return (float) $match[1] === 0.0;
return 1 === preg_match('/^rgba\([^,]+,[^,]+,[^,]+,\s*0(?:\.0*)?%?\s*\)$/', $color);
}

private static function paints(array $s): bool
{
foreach (array('box-shadow', 'filter', 'transform') as $property) {
if (!self::identityTransform($s['transform'])) return true;
foreach (array('box-shadow', 'filter') as $property) {
if ('none' !== $s[$property]) return true;
}
if ((float) $s['opacity'] !== 1.0 || !in_array($s['mix-blend-mode'], array('normal', 'none'), true)) return true;
foreach (array('overflow-x', 'overflow-y') as $property) {
if (in_array($s[$property], array('hidden', 'clip', 'scroll', 'auto'), true)) return true;
}
// CSSOM shorthands include color and defaults even when nothing paints.
$background = preg_replace('/rgba\(\s*0\s*,\s*0\s*,\s*0\s*,\s*0\s*\)|transparent/', '', $s['background']);
$background = preg_replace('/\b(?:none|repeat|scroll|auto|padding-box|border-box)\b|0%|\//', '', $background);
if ('' !== trim($background)) return true;
if (!preg_match('/^none(?:\s|$)/', $s['mask'])) return true;
if (!self::transparent($s['background-color'])) return true;
foreach (array('background-image', 'mask-image') as $property) {
if (!preg_match('/^none(?:\s*,\s*none)*$/i', trim($s[$property]))) return true;
}
foreach (array('border-top', 'border-right', 'border-bottom', 'border-left', 'outline') as $property) {
if (!preg_match('/\b(?:none|hidden)\b|(?:^|\s)0(?:px)?(?:\s|$)/', $s[$property]) && !str_contains($s[$property], 'transparent') && !preg_match('/rgba\([^)]*,\s*0\s*\)/', $s[$property])) return true;
}
Expand Down
2 changes: 1 addition & 1 deletion php-transformer/src/ArtifactCompiler/BoxTreeReport.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ private static function validate(mixed $tree, array $sources): ?string
if (!is_string($path) || !isset($sources[$path]) || hash('sha256', $sources[$path]) !== ($tree['source_hash'] ?? null)) return 'box_tree_identity_stale';
$viewports = $tree['viewports'] ?? null;
$nodes = $tree['nodes'] ?? null;
if (!is_array($viewports) || !isset($viewports['desktop'], $viewports['mobile']) || count($viewports) > BoxTree::MAX_VIEWPORTS || !is_array($nodes) || !$nodes || count($nodes) > BoxTree::MAX_NODES) return 'box_tree_bounds_invalid';
if (!is_array($viewports) || !$viewports || count($viewports) > BoxTree::MAX_VIEWPORTS || !is_array($nodes) || !$nodes || count($nodes) > BoxTree::MAX_NODES) return 'box_tree_bounds_invalid';
foreach ($viewports as $name => $viewport) {
if (!BoxTree::validId($name) || !is_array($viewport)) return 'box_tree_viewport_invalid';
foreach (array('width', 'height') as $dimension) {
Expand Down
4 changes: 2 additions & 2 deletions php-transformer/src/Contract/BoxTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ final class BoxTree
'flex-grow', 'flex-shrink', 'flex-basis', 'align-self', 'order',
'grid-template-columns', 'grid-template-rows', 'grid-auto-columns', 'grid-auto-rows', 'grid-auto-flow',
'grid-column-start', 'grid-column-end', 'grid-row-start', 'grid-row-end', 'justify-items', 'justify-self',
'background', 'border-top', 'border-right', 'border-bottom', 'border-left', 'border-radius',
'outline', 'box-shadow', 'mask', 'filter', 'opacity', 'mix-blend-mode', 'transform', 'z-index',
'background-color', 'background-image', 'border-top', 'border-right', 'border-bottom', 'border-left', 'border-radius',
'outline', 'box-shadow', 'mask-image', 'mask-mode', 'filter', 'opacity', 'mix-blend-mode', 'transform', 'z-index',
'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height',
);

Expand Down
Loading
Loading