Skip to content

Commit 57799a9

Browse files
jakejackson1claude
andauthored
Match child and sibling combinators and structural pseudo-classes against the open elements (mpdf#318)
The rules compiled for the matcher are matched right to left against the stack of open elements, and applied with the descendant rules, after them, in order of specificity and then of source order. That brings in div > p, h1 + p, h1 ~ p, and :first-child, :nth-child(), :first-of-type and :nth-of-type() on any element. Rules using them were dropped before. WriteHTML() tells the merger which element it is styling: the element whose start tag is being read, a block opened again after a forced page break, or a positioned block. A row written straight into a table sits in a tbody. The spans autoScriptToLang wraps a run of another script in, and the div standing in for a positioned block, are not matched, and the spans are not counted among their siblings. The document's frame is matched as body. A rule is only matched for an element whose ancestors have the ids, classes or tags its ancestor compounds name, so rules filed under the same tag stay cheap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 71b673f commit 57799a9

19 files changed

Lines changed: 1701 additions & 36 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ New features
102102
### CSS
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]
105+
* **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]
105106

106107
Performance
107108
-----------
@@ -373,7 +374,9 @@ These changes do not change output.
373374
* **Open elements.** `WriteHTML()` keeps a stack of the elements open in the HTML it reads, so that CSS rules can be matched against an element's parents, ancestors and earlier siblings rather than only the blocks mPDF lays out. Each element carries its position among its siblings and a record of the siblings before it. `Mpdf::getOpenElements()` reads it. [#533]
374375
* **Compiled selectors.** A rule whose selector the legacy parser cannot read is compiled into its compound selectors, the combinators between them and its specificity, and filed under its rightmost compound for the selector matcher. A selector list is split at the commas outside parentheses, brackets and strings, so `:is(h1, h2)` and `[title="a,b"]` stay whole. [#538] [#619]
375376

377+
[mpdf/mpdf#7]: https://github.com/mpdf/mpdf/issues/7
376378
[mpdf/mpdf#83]: https://github.com/mpdf/mpdf/issues/83
379+
[mpdf/mpdf#318]: https://github.com/mpdf/mpdf/issues/318
377380
[mpdf/mpdf#747]: https://github.com/mpdf/mpdf/issues/747
378381
[mpdf/mpdf#833]: https://github.com/mpdf/mpdf/issues/833
379382
[mpdf/mpdf#1010]: https://github.com/mpdf/mpdf/issues/1010
@@ -802,6 +805,7 @@ These changes do not change output.
802805
[#614]: https://github.com/GravityPDF/mpdf/pull/614
803806
[#615]: https://github.com/GravityPDF/mpdf/pull/615
804807
[#619]: https://github.com/GravityPDF/mpdf/pull/619
808+
[#620]: https://github.com/GravityPDF/mpdf/pull/620
805809
[#622]: https://github.com/GravityPDF/mpdf/pull/622
806810
[#623]: https://github.com/GravityPDF/mpdf/pull/623
807811
[#625]: https://github.com/GravityPDF/mpdf/pull/625

‎src/Css/CssMerger.php‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ public function merge($inherit, $tag, $attr)
146146
$this->mergeStylesheetSelectors($tag, $attr, $classes, $languageCode);
147147
$this->mergeTagSpecificSelectors($tag, $attr, $classes, $languageCode);
148148
$this->mergeDescendantSelectors($inherit, $tag, $attr, $classes, $languageCode);
149+
$this->mergeCompiledRules($tag, $attr);
149150
$this->mergeInlineStyle($tag, $attr);
150151

151152
return $this->cssProperties;
@@ -832,6 +833,30 @@ private function idClassKeys($tag, $id, $classes)
832833
return $keys;
833834
}
834835

836+
/**
837+
* Apply the rules whose selector only the matcher reads, such as div > p, h1 + p and li:first-child, matched
838+
* against the element and the open elements around it. They go with the descendant rules, after them, in the
839+
* order of their specificity and then of their position in the stylesheets.
840+
*
841+
* @param string $tag
842+
* @param array $attr
843+
* @return void
844+
*/
845+
protected function mergeCompiledRules($tag, $attr)
846+
{
847+
$classes = isset($attr['CLASS']) ? preg_split('/\s+/', $attr['CLASS'], -1, PREG_SPLIT_NO_EMPTY) : [];
848+
$path = [$this->mpdf, 'getStyledElementPath'];
849+
850+
foreach ($this->cssManager->getRules()->matchingDeclarations($tag, $attr['ID'], $classes, $path) as $properties) {
851+
if ($tag === 'TD' || $tag === 'TH') {
852+
$this->setDominanceFromProperties($properties, 9);
853+
}
854+
855+
$this->cssProperties = array_merge($this->cssProperties, $properties);
856+
$this->mergeBorderProperties($properties);
857+
}
858+
}
859+
835860
/**
836861
* Merge CSS properties into target array.
837862
*

‎src/Css/RuleSet.php‎

Lines changed: 125 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ class RuleSet
1111
{
1212

1313
/**
14-
* @var array[] Each rule, by its position in the stylesheets read: [compiled selector, declarations]
14+
* @var array[] Each rule, by its position in the stylesheets read: [compiled selector, declarations, the ancestors
15+
* it requires as requiredAncestors() gives them]
1516
*/
1617
private $rules = [];
1718

@@ -21,6 +22,19 @@ class RuleSet
2122
*/
2223
private $index = ['id' => [], 'class' => [], 'tag' => [], 'any' => []];
2324

25+
/**
26+
* @var SelectorMatcher
27+
*/
28+
private $matcher;
29+
30+
/**
31+
* An empty rule set
32+
*/
33+
public function __construct()
34+
{
35+
$this->matcher = new SelectorMatcher();
36+
}
37+
2438
/**
2539
* Adds a rule after those already read
2640
*
@@ -30,7 +44,7 @@ class RuleSet
3044
public function add(array $selector, array $declarations)
3145
{
3246
$position = count($this->rules);
33-
$this->rules[] = [$selector, $declarations];
47+
$this->rules[] = [$selector, $declarations, self::requiredAncestors($selector)];
3448

3549
self::file($this->index, $selector['compounds'][count($selector['compounds']) - 1], $position);
3650
}
@@ -50,10 +64,66 @@ public function candidates($tag, $id, array $classes)
5064
return self::collect($this->index, $tag, $id, $classes);
5165
}
5266

67+
/**
68+
* The declarations of the rules an element matches, in the order they apply: by specificity, then by position
69+
*
70+
* @param string $tag Uppercased
71+
* @param string $id Uppercased, or empty for none
72+
* @param string[] $classes Uppercased
73+
* @param callable $path Gives the open elements from the document down to the element, or null for none. Only
74+
* called when a rule is filed under the element
75+
*
76+
* @return array[]
77+
*/
78+
public function matchingDeclarations($tag, $id, array $classes, callable $path)
79+
{
80+
$candidates = $this->candidates($tag, $id, $classes);
81+
if (!$candidates) {
82+
return [];
83+
}
84+
85+
$path = call_user_func($path);
86+
if ($path === null || $path[count($path) - 1]['tag'] !== $tag) {
87+
return [];
88+
}
89+
90+
$ancestors = self::ancestorsOf($path);
91+
$matched = [];
92+
foreach ($candidates as $position) {
93+
list($selector, , $required) = $this->rules[$position];
94+
foreach ($required as $key) {
95+
if (!isset($ancestors[$key])) {
96+
continue 2;
97+
}
98+
}
99+
100+
if ($this->matcher->matches($selector, $path)) {
101+
$matched[] = $position;
102+
}
103+
}
104+
105+
$rules = $this->rules;
106+
usort($matched, function ($a, $b) use ($rules) {
107+
// Arrays of the same keys compare element by element: ids, then classes, then tags
108+
if ($rules[$a][0]['specificity'] != $rules[$b][0]['specificity']) {
109+
return $rules[$a][0]['specificity'] < $rules[$b][0]['specificity'] ? -1 : 1;
110+
}
111+
112+
return $a - $b;
113+
});
114+
115+
$declarations = [];
116+
foreach ($matched as $position) {
117+
$declarations[] = $this->rules[$position][1];
118+
}
119+
120+
return $declarations;
121+
}
122+
53123
/**
54124
* @param int $position
55125
*
56-
* @return array The rule at a position, as it is kept: [compiled selector, declarations]
126+
* @return array The rule at a position, as it is kept: [compiled selector, declarations, required ancestors]
57127
*/
58128
public function rule($position)
59129
{
@@ -105,4 +175,56 @@ private static function collect(array $index, $tag, $id, array $classes)
105175

106176
return $positions;
107177
}
178+
179+
/**
180+
* A key for each compound of a selector that an ancestor of the element has to match: the compound's first id,
181+
* else its first class, else its tag. A compound followed by a descendant or child combinator names an ancestor,
182+
* since an ancestor of a sibling is one too. A rule is only matched for an element whose ancestors give every key
183+
*
184+
* @param array $selector
185+
*
186+
* @return string[] Each key prefixed with I, C or T for an id, a class or a tag
187+
*/
188+
private static function requiredAncestors(array $selector)
189+
{
190+
$keys = [];
191+
foreach ($selector['combinators'] as $i => $combinator) {
192+
if ($combinator !== ' ' && $combinator !== '>') {
193+
continue;
194+
}
195+
196+
$compound = $selector['compounds'][$i];
197+
if ($compound['ids']) {
198+
$keys[] = 'I' . $compound['ids'][0];
199+
} elseif ($compound['classes']) {
200+
$keys[] = 'C' . $compound['classes'][0];
201+
} elseif ($compound['tag'] !== null) {
202+
$keys[] = 'T' . $compound['tag'];
203+
}
204+
}
205+
206+
return $keys;
207+
}
208+
209+
/**
210+
* @param array[] $path
211+
*
212+
* @return array<string, true> The keys requiredAncestors() gives for the ids, classes and tags of the element's
213+
* ancestors, the document's frame being body
214+
*/
215+
private static function ancestorsOf(array $path)
216+
{
217+
$keys = ['T' . 'BODY' => true]; // the document's frame
218+
for ($depth = count($path) - 2; $depth > 0; $depth--) {
219+
$keys['T' . $path[$depth]['tag']] = true;
220+
if ($path[$depth]['id'] !== '') {
221+
$keys['I' . $path[$depth]['id']] = true;
222+
}
223+
foreach ($path[$depth]['classes'] as $class) {
224+
$keys['C' . $class] = true;
225+
}
226+
}
227+
228+
return $keys;
229+
}
108230
}

0 commit comments

Comments
 (0)