Skip to content

Commit 98110b6

Browse files
jakejackson1claude
andcommitted
Apply descendant rules through inline ancestors and blocks inside table cells (mpdf#830)
The legacy engine only looks for the ancestors a descendant rule names among the blocks and table parts that open a level of its rules, so span em, or .note b for a <span class="note">, never applied, nor div b for a div inside a table cell, nor table tbody td where the tbody is left out. Each descendant rule the legacy parser stores is compiled too. The matcher applies it only to an element with an ancestor that opened no level, and only where the legacy engine could not match it, so nothing is applied twice and the order the legacy engine gives the rest stays. Each open element's frame records whether it opened a level, as the merger reports when it styles the element. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fd92084 commit 98110b6

15 files changed

Lines changed: 601 additions & 40 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ New features
103103

104104
* **An id written with classes.** Selectors such as `p#note.warning`, `p.warning#note`, `#note.warning` and `p.a.b#note` match, on their own and as parts of descendant rules, in any order of id and classes. They are applied after `p#note`. A selector with a class or id followed by something mPDF cannot match, such as `.a:hover` or `#note::before`, is dropped like any other selector mPDF cannot match. [#527] [#568]
105105
* **Child and sibling combinators, and structural pseudo-classes.** `div > p`, `h1 + p`, `h1 ~ p`, and `:first-child`, `:nth-child()`, `:first-of-type` and `:nth-of-type()` on any element, are matched against the elements open around the one being styled. Rules using them were dropped before, so a document that has them changes. They are applied with the descendant rules, after them, in order of specificity and then of source order. [mpdf/mpdf#7] [mpdf/mpdf#318] [#538] [#620]
106+
* **Descendant rules through inline elements.** A descendant rule whose ancestor is an inline element, a block inside a table cell, or the `tbody` a table leaves out, such as `span em`, or `.note b` for a `<span class="note">`, applies. [mpdf/mpdf#830] [#538] [#621]
106107

107108
Performance
108109
-----------
@@ -378,6 +379,7 @@ These changes do not change output.
378379
[mpdf/mpdf#83]: https://github.com/mpdf/mpdf/issues/83
379380
[mpdf/mpdf#318]: https://github.com/mpdf/mpdf/issues/318
380381
[mpdf/mpdf#747]: https://github.com/mpdf/mpdf/issues/747
382+
[mpdf/mpdf#830]: https://github.com/mpdf/mpdf/issues/830
381383
[mpdf/mpdf#833]: https://github.com/mpdf/mpdf/issues/833
382384
[mpdf/mpdf#1010]: https://github.com/mpdf/mpdf/issues/1010
383385
[mpdf/mpdf#1089]: https://github.com/mpdf/mpdf/issues/1089
@@ -806,6 +808,7 @@ These changes do not change output.
806808
[#615]: https://github.com/GravityPDF/mpdf/pull/615
807809
[#619]: https://github.com/GravityPDF/mpdf/pull/619
808810
[#620]: https://github.com/GravityPDF/mpdf/pull/620
811+
[#621]: https://github.com/GravityPDF/mpdf/pull/621
809812
[#622]: https://github.com/GravityPDF/mpdf/pull/622
810813
[#623]: https://github.com/GravityPDF/mpdf/pull/623
811814
[#625]: https://github.com/GravityPDF/mpdf/pull/625

‎src/Css/CssMerger.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,8 @@ protected function mergeTableCascadingCss($inherit, $tag, $attr, $classes)
188188
return;
189189
}
190190

191+
$this->mpdf->markStyledElementAsLevel();
192+
191193
if ($inherit === 'TOPTABLE') {
192194
// Save Cascading CSS e.g. "div.topic p" at this block level
193195
if (isset($this->mpdf->blk[$this->mpdf->blklvl]['cascadeCSS'])) {
@@ -279,6 +281,7 @@ protected function mergeBlockCascadingCss($inherit, $tag, $attr, $classes)
279281
// Set the new block info
280282
if ($this->sideEffects) {
281283
$this->mpdf->blk[$this->mpdf->blklvl] = $currentBlock;
284+
$this->mpdf->markStyledElementAsLevel();
282285
}
283286

284287
// Block properties which are inherited

‎src/Css/CssParser.php‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,8 @@ class CssParser
121121
private $nthChildFormulas = ['TR' => [], 'TD' => [], 'TH' => []];
122122

123123
/**
124-
* @var array[] The rules of the last CSS parsed whose selector the legacy parser cannot read, each compiled:
125-
* [compiled selector, declarations], in the order they were written
124+
* @var array[] The rules of the last CSS parsed for the matcher, each compiled: [compiled selector, declarations,
125+
* whether the legacy parser stores it too], in the order they were written
126126
*/
127127
private $compiledRules = [];
128128

@@ -221,9 +221,11 @@ public function getCascadeCss()
221221
}
222222

223223
/**
224-
* The rules of the last CSS parsed whose selector the legacy parser cannot read, compiled for the matcher
224+
* The rules of the last CSS parsed for the matcher: those whose selector the legacy parser cannot read, and the
225+
* descendant rules it stores, which the matcher applies through the ancestors the legacy engine does not look at
225226
*
226-
* @return array[] Each [compiled selector, declarations], in the order they were written
227+
* @return array[] Each [compiled selector, declarations, whether the legacy parser stores it too], in the order
228+
* they were written
227229
*/
228230
public function getCompiledRules()
229231
{
@@ -343,6 +345,9 @@ private function processCssSelector($written, $classProperties)
343345

344346
$cascadeCSS = Arrays::uniqueRecursiveMerge($cascadeCSS, $classProperties);
345347
$cascadeCSS['depth'] = $level;
348+
349+
// The legacy engine only looks for the ancestors a descendant rule names among blocks and table parts
350+
$this->compileRule($written, $classProperties, true);
346351
}
347352

348353
/**
@@ -389,9 +394,10 @@ private function isLegacySelector(array $levels)
389394
*
390395
* @param string $selector As written
391396
* @param array $classProperties
397+
* @param bool $legacy Whether the legacy parser stores it too
392398
* @return void
393399
*/
394-
private function compileRule($selector, array $classProperties)
400+
private function compileRule($selector, array $classProperties, $legacy = false)
395401
{
396402
if (!$classProperties) {
397403
return;
@@ -402,7 +408,7 @@ private function compileRule($selector, array $classProperties)
402408
// The universal selector changes which elements existing documents style, so it waits for #530 and the
403409
// standard cascade option
404410
if ($compiled !== null && !$compiled['universal']) {
405-
$this->compiledRules[] = [$compiled, $classProperties];
411+
$this->compiledRules[] = [$compiled, $classProperties, $legacy];
406412
}
407413
}
408414

‎src/Css/RuleSet.php‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,17 @@
66
* Compiled stylesheet rules, filed under the rightmost compound of their selector as browsers file them: by its id,
77
* else its first class, else its tag, else with the rules any element may match. An element then only has to be
88
* matched against the rules filed under its own id, classes and tag, and those.
9+
*
10+
* The descendant rules the legacy engine applies too are filed apart. They are only looked at for an element with an
11+
* ancestor that opened no level of the legacy descendant rules, such as an inline element, since the legacy engine
12+
* matches the rest.
913
*/
1014
class RuleSet
1115
{
1216

1317
/**
1418
* @var array[] Each rule, by its position in the stylesheets read: [compiled selector, declarations, the ancestors
15-
* it requires as requiredAncestors() gives them]
19+
* it requires as requiredAncestors() gives them, whether the legacy engine applies it too]
1620
*/
1721
private $rules = [];
1822

@@ -22,6 +26,11 @@ class RuleSet
2226
*/
2327
private $index = ['id' => [], 'class' => [], 'tag' => [], 'any' => []];
2428

29+
/**
30+
* @var array The descendant rules the legacy engine applies too, filed in the same way
31+
*/
32+
private $legacyIndex = ['id' => [], 'class' => [], 'tag' => [], 'any' => []];
33+
2534
/**
2635
* @var SelectorMatcher Matches each rule filed under an element against the open elements around it
2736
*/
@@ -40,13 +49,21 @@ public function __construct()
4049
*
4150
* @param array $selector A selector SelectorCompiler::compile() compiled
4251
* @param array $declarations Its normalised declarations
52+
* @param bool $legacy For a rule the legacy engine applies too: match it only where the legacy engine cannot,
53+
* such as through an inline element or another ancestor that opens no level of its
54+
* descendant rules
4355
*/
44-
public function add(array $selector, array $declarations)
56+
public function add(array $selector, array $declarations, $legacy = false)
4557
{
4658
$position = count($this->rules);
47-
$this->rules[] = [$selector, $declarations, self::requiredAncestors($selector)];
59+
$this->rules[] = [$selector, $declarations, self::requiredAncestors($selector), $legacy];
4860

49-
self::file($this->index, $selector['compounds'][count($selector['compounds']) - 1], $position);
61+
$subject = $selector['compounds'][count($selector['compounds']) - 1];
62+
if ($legacy) {
63+
self::file($this->legacyIndex, $subject, $position);
64+
} else {
65+
self::file($this->index, $subject, $position);
66+
}
5067
}
5168

5269
/**
@@ -78,7 +95,8 @@ public function candidates($tag, $id, array $classes)
7895
public function matchingDeclarations($tag, $id, array $classes, callable $path)
7996
{
8097
$candidates = $this->candidates($tag, $id, $classes);
81-
if (!$candidates) {
98+
$legacyCandidates = self::collect($this->legacyIndex, $tag, $id, $classes);
99+
if (!$candidates && !$legacyCandidates) {
82100
return [];
83101
}
84102

@@ -87,17 +105,21 @@ public function matchingDeclarations($tag, $id, array $classes, callable $path)
87105
return [];
88106
}
89107

108+
if ($legacyCandidates && self::hasAncestorOpeningNoLevel($path)) {
109+
$candidates = array_merge($candidates, $legacyCandidates);
110+
}
111+
90112
$ancestors = self::ancestorsOf($path);
91113
$matched = [];
92114
foreach ($candidates as $position) {
93-
list($selector, , $required) = $this->rules[$position];
115+
list($selector, , $required, $legacy) = $this->rules[$position];
94116
foreach ($required as $key) {
95117
if (!isset($ancestors[$key])) {
96118
continue 2;
97119
}
98120
}
99121

100-
if ($this->matcher->matches($selector, $path)) {
122+
if ($this->matcher->matches($selector, $path) && !($legacy && $this->matcher->matches($selector, $path, true))) {
101123
$matched[] = $position;
102124
}
103125
}
@@ -123,7 +145,8 @@ public function matchingDeclarations($tag, $id, array $classes, callable $path)
123145
/**
124146
* @param int $position
125147
*
126-
* @return array The rule at a position, as it is kept: [compiled selector, declarations, required ancestors]
148+
* @return array The rule at a position, as it is kept: [compiled selector, declarations, required ancestors,
149+
* whether the legacy engine applies it too]
127150
*/
128151
public function rule($position)
129152
{
@@ -230,4 +253,24 @@ private static function ancestorsOf(array $path)
230253

231254
return $keys;
232255
}
256+
257+
/**
258+
* Whether an ancestor of the element opened no level of the legacy descendant rules, such as an inline element or
259+
* a block inside a table cell. Only then can a descendant rule the legacy engine applies too match where the
260+
* legacy engine does not, so the rules filed in the legacy index are only looked at for such an element
261+
*
262+
* @param array[] $path The open elements from the document down to the element, with the element last
263+
*
264+
* @return bool
265+
*/
266+
private static function hasAncestorOpeningNoLevel(array $path)
267+
{
268+
for ($depth = count($path) - 2; $depth > 0; $depth--) {
269+
if (!$path[$depth]['level']) {
270+
return true;
271+
}
272+
}
273+
274+
return false;
275+
}
233276
}

‎src/Css/SelectorMatcher.php‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,16 @@ class SelectorMatcher
1818
*
1919
* @param array $selector A selector SelectorCompiler::compile() compiled
2020
* @param array[] $path The open elements from the document down to the element
21+
* @param bool $legacyView Whether to match as the legacy engine does: a descendant combinator only looks at the
22+
* ancestors that opened a level of the legacy descendant rules
2123
*
2224
* @return bool
2325
*/
24-
public function matches(array $selector, array $path)
26+
public function matches(array $selector, array $path, $legacyView = false)
2527
{
2628
$depth = count($path) - 1;
2729

28-
return $this->matchesFrom($selector, count($selector['compounds']) - 1, $path, $depth - 1, $path[$depth]['nthChild'] - 1);
30+
return $this->matchesFrom($selector, count($selector['compounds']) - 1, $path, $depth - 1, $path[$depth]['nthChild'] - 1, $legacyView);
2931
}
3032

3133
/**
@@ -39,10 +41,11 @@ public function matches(array $selector, array $path)
3941
* @param int $parent The depth on $path of the element's parent, or -1 for the document itself
4042
* @param int $index The element's index among its parent's children, from 0. At the number of children the parent
4143
* has closed, it is the open element at the next depth
44+
* @param bool $legacyView Whether to match as the legacy engine does, as matches() takes it
4245
*
4346
* @return bool
4447
*/
45-
private function matchesFrom(array $selector, $compound, array $path, $parent, $index)
48+
private function matchesFrom(array $selector, $compound, array $path, $parent, $index, $legacyView)
4649
{
4750
if (!$this->matchesCompound($selector['compounds'][$compound], $path, $parent, $index)) {
4851
return false;
@@ -55,23 +58,24 @@ private function matchesFrom(array $selector, $compound, array $path, $parent, $
5558
$compound--;
5659
switch ($selector['combinators'][$compound]) {
5760
case '>':
58-
return $parent >= 0 && $this->matchesFrom($selector, $compound, $path, $parent - 1, $path[$parent]['nthChild'] - 1);
61+
return $parent >= 0 && $this->matchesFrom($selector, $compound, $path, $parent - 1, $path[$parent]['nthChild'] - 1, $legacyView);
5962

6063
case ' ':
6164
for ($depth = $parent; $depth >= 0; $depth--) {
62-
if ($this->matchesFrom($selector, $compound, $path, $depth - 1, $path[$depth]['nthChild'] - 1)) {
65+
if ((!$legacyView || $path[$depth]['level'])
66+
&& $this->matchesFrom($selector, $compound, $path, $depth - 1, $path[$depth]['nthChild'] - 1, $legacyView)) {
6367
return true;
6468
}
6569
}
6670

6771
return false;
6872

6973
case '+':
70-
return $parent >= 0 && $index > 0 && $this->matchesFrom($selector, $compound, $path, $parent, $index - 1);
74+
return $parent >= 0 && $index > 0 && $this->matchesFrom($selector, $compound, $path, $parent, $index - 1, $legacyView);
7175

7276
default:
7377
for ($sibling = $index - 1; $parent >= 0 && $sibling >= 0; $sibling--) {
74-
if ($this->matchesFrom($selector, $compound, $path, $parent, $sibling)) {
78+
if ($this->matchesFrom($selector, $compound, $path, $parent, $sibling, $legacyView)) {
7579
return true;
7680
}
7781
}

‎src/CssManager.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ class CssManager
8888
public $tbCSSlvl = 0;
8989

9090
/**
91-
* @var RuleSet The rules whose selector the legacy parser cannot read, compiled, from every stylesheet read
91+
* @var RuleSet The rules compiled for the matcher, from every stylesheet read
9292
*/
9393
private $rules;
9494

@@ -131,14 +131,14 @@ public function readCss($html)
131131
$this->cascadeCSS = Arrays::uniqueRecursiveMerge($this->cascadeCSS, $this->cssParser->getCascadeCss());
132132

133133
foreach ($this->cssParser->getCompiledRules() as $rule) {
134-
$this->rules->add($rule[0], $rule[1]);
134+
$this->rules->add($rule[0], $rule[1], $rule[2]);
135135
}
136136

137137
return $html;
138138
}
139139

140140
/**
141-
* The rules whose selector the legacy parser cannot read, compiled, from every stylesheet read so far
141+
* The rules compiled for the matcher, from every stylesheet read so far
142142
*
143143
* @return RuleSet
144144
*/

‎src/Mpdf.php‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15104,23 +15104,25 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1510415104
$this->blk[$this->blklvl]['tag'] = $te; // mPDF 6
1510515105
}
1510615106
$this->closeElementsImpliedBy($tag, $floor);
15107-
$this->startElement($tag, $attr, $selfClosing);
15107+
$this->startElement($tag, $attr, $selfClosing, false);
1510815108
continue;
1510915109
}
1511015110

1511115111
$this->closeElementsImpliedBy($tag, $floor);
1511215112
$token = $i;
1511315113
// The <div> standing in for a positioned block has had the block's rules, through its style
1511415114
$outerElement = $this->styledElement;
15115-
$this->styledElement = !$standIn && $this->isDocumentElement($tag, $attr) ? ['path' => $this->openElements, 'tag' => $tag, 'attr' => $attr] : null;
15115+
$this->styledElement = !$standIn && $this->isDocumentElement($tag, $attr) ? ['path' => $this->openElements, 'tag' => $tag, 'attr' => $attr, 'level' => false] : null;
1511615116
$this->tag->OpenTag($tag, $attr, $a, $i); // mPDF 6
1511715117
// Unless it put back a page-break-inside: avoid block, which rewinds the parser to that block's start
1511815118
// tag and the open elements to how they were there
1511915119
if ($i === $token) {
1512015120
if ($standIn) {
15121+
// Its content matches the block's descendant rules, as the content of a block does
15122+
$this->openElements[count($this->openElements) - 1]['level'] = true;
1512115123
$standIn = false;
1512215124
} else {
15123-
$this->startElement($tag, $attr, $selfClosing);
15125+
$this->startElement($tag, $attr, $selfClosing, $this->styledElement !== null && $this->styledElement['level']);
1512415126
}
1512515127
}
1512615128
// Held on to, the copy of the stack would make recording each closed child copy its parent's record
@@ -15307,7 +15309,7 @@ function WriteFixedPosHTML($html, $x, $y, $w, $h, $overflow = 'visible', $boundi
1530715309
$this->blk[1]['attr'] = $attr;
1530815310
$this->Reset();
1530915311
$outerElement = $this->styledElement;
15310-
$this->styledElement = $this->fixedPosBlockElements === null ? null : ['path' => $this->fixedPosBlockElements, 'tag' => null, 'attr' => []];
15312+
$this->styledElement = $this->fixedPosBlockElements === null ? null : ['path' => $this->fixedPosBlockElements, 'tag' => null, 'attr' => [], 'level' => false];
1531115313
$p = $this->cssManager->MergeCSS('BLOCK', $tag, $attr);
1531215314
$this->styledElement = $outerElement;
1531315315
$this->fixedPosBlockCascadeCSS = $this->blk[1]['cascadeCSS'];

0 commit comments

Comments
 (0)