Skip to content

Commit ef2ccd2

Browse files
jakejackson1claude
andcommitted
Match :root, html, :link and :any-link, and read rem against html's font size
In the standard CSS mode, :link and :any-link match a link with an href, and :visited, :hover, :focus, :active, :focus-within, :focus-visible and :target never match, so :not(:hover) always does. mPDF has no html element, so html and :root are matched as the parent of body: their rules are merged into body's, and body's own rules win over them. rem is read against html's font size, which starts from the default font size, rather than against body's or a table's. body's relative size is read against html's. Rules that never match record no class names for the legacy merger. The legacy mode drops all of these as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b19356c commit ef2ccd2

23 files changed

Lines changed: 1205 additions & 55 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ Read this section before upgrading from upstream mPDF. Each entry says what chan
5252
* `<div align>` passes its alignment on to what it holds, and `<li type>` beats the marker the item inherits from its list.
5353
* Attributes mPDF ignored now take effect: `<hr align>`, `<hr size>`, `<img align>` (float left or right, or vertical alignment), `<img border>`, `<thead align>`, and `<table border>` wider than 1.
5454
* A table's `border` gives each cell a 1px border of its own, which a rule for the table's border leaves alone. Before, the cells copied the table's border.
55+
* **`rem` is read against the font size of `html`, in standard mode**, as in a browser. It was read against the font size of `body`, and inside a table against the table's. Now `1rem` is the default font size, from the `default_font_size` configuration or `SetDefaultFontSize()`, unless an `html` or `:root` rule sizes `html`: with `html { font-size: 62.5% }`, `1.6rem` is the default size again. A `body { font-size }` rule no longer changes it. To keep the old sizes, give them in `em` or points, or set `'cssMode' => \Mpdf\CssMode::LEGACY`. [#529] [#642]
5556

5657
New features
5758
------------
@@ -124,6 +125,7 @@ New features
124125
* **Pseudo-classes that look at what follows an element.** `:last-child`, `:nth-last-child()`, `:only-child`, `:last-of-type`, `:nth-last-of-type()`, `:only-of-type` and `:empty` match in the flow, in tables, headers and footers, and positioned blocks. Rules using them were dropped before, so a document that has them changes. Set `'cssMode' => \Mpdf\CssMode::LEGACY` to keep dropping them. [#537] [#634]
125126
* `WriteHTML()` reads ahead through the HTML it is given to count each element's children. An element still open at the end of a call that leaves it open is not known in full, so these do not match its children in that call, and nor does `:not()` of them.
126127
* `:empty` matches as in browsers: an element holding white space is not empty, and one holding only a comment is. A table cell holding only white space is empty, as mPDF strips it.
128+
* **`:root`, `html`, `:link` and `:any-link`, in standard mode.** `a:link` and `:any-link` match a link with an `href`. mPDF has no `html` element, so `html` and `:root` match it as the parent of `body`: their rules reach the text as a parent's would, and rules for `body` win over them. `:visited`, `:hover`, `:focus`, `:active`, `:focus-within`, `:focus-visible` and `:target` never match, as a PDF is never visited or hovered, so `:not(:hover)` always does. Rules using them were dropped before, so a document that has them changes. Set `'cssMode' => \Mpdf\CssMode::LEGACY` to keep dropping them. [#529] [#642]
127129

128130
Performance
129131
-----------
@@ -806,6 +808,7 @@ These changes do not change output.
806808
[#526]: https://github.com/GravityPDF/mpdf/issues/526
807809
[#527]: https://github.com/GravityPDF/mpdf/issues/527
808810
[#528]: https://github.com/GravityPDF/mpdf/issues/528
811+
[#529]: https://github.com/GravityPDF/mpdf/issues/529
809812
[#531]: https://github.com/GravityPDF/mpdf/issues/531
810813
[#532]: https://github.com/GravityPDF/mpdf/issues/532
811814
[#533]: https://github.com/GravityPDF/mpdf/issues/533
@@ -865,3 +868,4 @@ These changes do not change output.
865868
[#638]: https://github.com/GravityPDF/mpdf/pull/638
866869
[#639]: https://github.com/GravityPDF/mpdf/pull/639
867870
[#641]: https://github.com/GravityPDF/mpdf/pull/641
871+
[#642]: https://github.com/GravityPDF/mpdf/pull/642

‎src/Css/CssMerger.php‎

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use Mpdf\CssManager;
88
use Mpdf\Exception\InvalidArgumentException;
99
use Mpdf\Mpdf;
10+
use Mpdf\SizeConverter;
1011
use Mpdf\Utils\Arrays;
1112

1213
class CssMerger
@@ -62,6 +63,11 @@ class CssMerger
6263
*/
6364
private $presentationalHints;
6465

66+
/**
67+
* @var SizeConverter
68+
*/
69+
private $sizeConverter;
70+
6571
/**
6672
* @var bool When true, state outside this object will be modified
6773
* @internal self::previewBlockCss() uses this property to look ahead without affecting state
@@ -76,7 +82,8 @@ public function __construct(
7682
InlinePropertyConverter $inlinePropertyConverter,
7783
ColorConverter $colorConverter,
7884
BorderMerger $borderMerger,
79-
PresentationalHints $presentationalHints
85+
PresentationalHints $presentationalHints,
86+
SizeConverter $sizeConverter
8087
) {
8188
$this->mpdf = $mpdf;
8289
$this->normalizeProperties = $normalizeProperties;
@@ -86,6 +93,7 @@ public function __construct(
8693
$this->colorConverter = $colorConverter;
8794
$this->borderMerger = $borderMerger;
8895
$this->presentationalHints = $presentationalHints;
96+
$this->sizeConverter = $sizeConverter;
8997
}
9098

9199
/**
@@ -213,8 +221,9 @@ private function mergeInCascadeOrder($inherit, $tag, array $attr)
213221
// Merged outside the document's elements, and written to by Mpdf::SetDefaultBodyCSS() and the like
214222
$important = $this->cssManager->getImportantCss();
215223
$importantDefault = $this->cssManager->getDefaultImportantCss();
216-
$rules = [isset($this->cssManager->CSS['BODY']) ? $this->cssManager->CSS['BODY'] : []];
217-
$importantRules = isset($important['BODY']) ? [$important['BODY']] : [];
224+
$this->setMergedCss(isset($this->cssManager->CSS['BODY']) ? $this->cssManager->CSS['BODY'] : [], false);
225+
$rules = [];
226+
$importantRules = array_merge(isset($important['BODY']) ? [$important['BODY']] : [], $this->mergeDocumentRules());
218227
$importantDefaultRules = isset($importantDefault['BODY']) ? [$importantDefault['BODY']] : [];
219228
} else {
220229
list($rules, $importantRules) = $this->cssManager->getRules()->matchingDeclarations($tag, $id, $classes, $path);
@@ -227,6 +236,42 @@ private function mergeInCascadeOrder($inherit, $tag, array $attr)
227236
return $this->cssProperties;
228237
}
229238

239+
/**
240+
* Merges html's rules into body's CSS, and body's own rules again over them. mPDF has no html element: the
241+
* document's frame stands for body, and html is matched as its parent, so html's declarations, its !important
242+
* ones included, reach the text as a parent's would, and lose to body's. Both win over what SetDefaultBodyCSS() and
243+
* the like set.
244+
*
245+
* html's font size, read against the default font size, is the root's, which rem and body's own size are read
246+
* against
247+
*
248+
* @return array[] The !important declarations of body's rules, which apply after body's style
249+
*/
250+
private function mergeDocumentRules()
251+
{
252+
$rules = $this->cssManager->getRules();
253+
$path = $this->mpdf->getDocumentPath();
254+
$initial = $this->mpdf->initial_font_size;
255+
$this->mpdf->root_font_size = $initial;
256+
257+
list($html, $importantHtml) = $rules->documentDeclarations(true, $path);
258+
foreach (array_merge($html, $importantHtml) as $properties) {
259+
if (isset($properties['FONT-SIZE'])) {
260+
$size = $this->sizeConverter->convertFontSize($properties['FONT-SIZE'], $initial / Mpdf::SCALE, $initial);
261+
if ($size !== null) {
262+
$this->mpdf->root_font_size = $size;
263+
$properties['FONT-SIZE'] = $size . 'pt';
264+
}
265+
}
266+
$this->setMergedCss($properties, false);
267+
}
268+
269+
list($body, $importantBody) = $rules->documentDeclarations(false, $path);
270+
$this->mergeEach($body, false);
271+
272+
return $importantBody;
273+
}
274+
230275
/**
231276
* Merges sets of properties, each over those before it
232277
*

‎src/Css/CssParser.php‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -340,13 +340,6 @@ private function processCssSelector($written, $classProperties, array $important
340340
{
341341
$selector = strtoupper($written);
342342

343-
// store classes in an index for faster lookups
344-
if (strpos($selector, '.') !== false && preg_match_all('/\.([a-zA-Z0-9_\-]+)/', $selector, $matches)) {
345-
foreach ($matches[1] as $className) {
346-
$this->usedClassNames[$className] = true;
347-
}
348-
}
349-
350343
// Close up each nth-child argument, e.g. (2N + 1), so the selector still splits into its parts on whitespace
351344
$selector = preg_replace_callback('/NTH-CHILD\(([^)]*)\)/', function ($m) {
352345
return 'NTH-CHILD(' . preg_replace('/\s+/', '', $m[1]) . ')';
@@ -417,8 +410,8 @@ private function storeByKey($key, array $classProperties, array $important)
417410
}
418411

419412
/**
420-
* Record what the merger needs to know about the key of one compound selector of a stored rule: how many classes
421-
* it names, and its nth-child formula.
413+
* Record what the merger needs to know about the key of one compound selector of a stored rule: the classes it
414+
* names and how many, and its nth-child formula. A rule that is not stored, as one naming :hover, records nothing.
422415
*
423416
* @param string $key A key SelectorParser::parseSimpleSelector() made, e.g. P>>CLASS>>A.B or TD>>SELECTORNTHCHILD>>2N+1
424417
* @return void
@@ -428,6 +421,11 @@ private function indexStoredKey($key)
428421
$classes = strpos($key, 'CLASS>>');
429422
if ($classes !== false) {
430423
$this->maxClassDepth = max($this->maxClassDepth, substr_count($key, '.', $classes) + 1);
424+
425+
preg_match_all('/\.([a-zA-Z0-9_\-]+)/', '.' . substr($key, $classes + 7), $matches);
426+
foreach ($matches[1] as $className) {
427+
$this->usedClassNames[$className] = true;
428+
}
431429
}
432430

433431
if (preg_match('/^(TR|TD|TH)>>SELECTORNTHCHILD>>(.*)$/', $key, $m) && !isset($this->nthChildFormulas[$m[1]][$key])) {
@@ -472,7 +470,7 @@ private function compileRule($selector, array $classProperties, array $important
472470
$compiled = $this->selectorCompiler->compile($selector);
473471

474472
// The universal selector changes which elements existing documents style, so it waits for #530
475-
if ($compiled !== null && !$compiled['universal']) {
473+
if ($compiled !== null && !$compiled['universal'] && !$compiled['never']) {
476474
$this->compiledRules[] = [$compiled, $classProperties, $important];
477475
}
478476
}

‎src/Css/RuleSet.php‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,38 @@ public function matchingDeclarations($tag, $id, array $classes, callable $path)
104104
}
105105
}
106106

107+
return $this->inCascadeOrder($matched);
108+
}
109+
110+
/**
111+
* The declarations of the rules html or body matches, in the order they apply. mPDF has no html element, and
112+
* matches html as the parent of body, which the document's frame stands for
113+
*
114+
* @param bool $html Whether for html rather than body
115+
* @param array[] $path The document's frame alone
116+
*
117+
* @return array[] [the normal declarations of each rule, the !important declarations of each rule with any]
118+
*/
119+
public function documentDeclarations($html, array $path)
120+
{
121+
$matched = [];
122+
foreach ($this->candidates($html ? 'HTML' : 'BODY', '', []) as $position) {
123+
if ($this->matcher->matchesDocumentElement($this->rules[$position][0], $path, $html)) {
124+
$matched[] = $position;
125+
}
126+
}
127+
128+
return $this->inCascadeOrder($matched);
129+
}
130+
131+
/**
132+
* @param int[] $matched The positions of the rules an element matches
133+
*
134+
* @return array[] Their declarations, in the order they apply: by specificity, then by position. [the normal
135+
* declarations of each rule, the !important declarations of each rule with any]
136+
*/
137+
private function inCascadeOrder(array $matched)
138+
{
107139
$rules = $this->rules;
108140
usort($matched, function ($a, $b) use ($rules) {
109141
// Arrays of the same keys compare element by element: ids, then classes, then tags
@@ -137,6 +169,9 @@ public function rule($position)
137169
}
138170

139171
/**
172+
* Files a rule under its id, class or tag. With none, :root files it under html, and :link under the tags it
173+
* matches
174+
*
140175
* @param array $index
141176
* @param array $subject The rightmost compound of a rule's selector
142177
* @param int $position The rule's position
@@ -149,6 +184,11 @@ private static function file(array &$index, array $subject, $position)
149184
$index['class'][$subject['classes'][0]][] = $position;
150185
} elseif ($subject['tag'] !== null) {
151186
$index['tag'][$subject['tag']][] = $position;
187+
} elseif (in_array(['root'], $subject['pseudos'], true)) {
188+
$index['tag']['HTML'][] = $position;
189+
} elseif (in_array(['link'], $subject['pseudos'], true)) {
190+
$index['tag']['A'][] = $position;
191+
$index['tag']['AREA'][] = $position;
152192
} else {
153193
$index['any'][] = $position;
154194
}
@@ -219,11 +259,11 @@ private static function requiredAncestors(array $selector)
219259
* @param array[] $path The open elements from the document down to the element, with the element last
220260
*
221261
* @return array<string, true> The keys requiredAncestors() gives for the ids, classes and tags of the element's
222-
* ancestors, the document's frame being body
262+
* ancestors, the document's frame being body, with html above it
223263
*/
224264
private static function ancestorsOf(array $path)
225265
{
226-
$keys = ['T' . 'BODY' => true]; // the document's frame
266+
$keys = ['T' . 'HTML' => true, 'T' . 'BODY' => true]; // html, and the document's frame
227267
for ($depth = count($path) - 2; $depth > 0; $depth--) {
228268
$keys['T' . $path[$depth]['tag']] = true;
229269
if ($path[$depth]['id'] !== '') {

‎src/Css/SelectorCompiler.php‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
* - combinators: the combinator after each compound but the last, one of ' ', '>', '+' and '~'
1717
* - specificity: [ids, classes and attributes and pseudo-classes, tags]
1818
* - universal: whether it names the universal selector *
19+
* - never: whether one of its compounds holds a pseudo-class that no element in a PDF matches, so that it matches
20+
* nothing
1921
*
2022
* Attribute selectors are held as [name, operator, value, case-insensitive]: the name uppercased, as the tokenizer
2123
* names attributes, and the operator empty for [name]. Values are compared case-insensitively, and held lowercased,
@@ -26,6 +28,10 @@
2628
* written as, ['only-child'], ['only-of-type'] and ['empty'], ['lang', ranges] with each language range lowercased,
2729
* and ['not', selectors] and ['is', selectors] with each selector compiled. :where() is held as :is(), its
2830
* specificity being the only difference.
31+
*
32+
* Some pseudo-classes have a fixed answer in a PDF, where no link is visited and nothing is hovered over or focused.
33+
* :root is held as ['root'], and :link and :any-link as ['link']. :visited, :hover, :focus and the other states a
34+
* reader acts out are held as ['never']. They count as a class, and matter inside :not(), which then matches.
2935
*/
3036
class SelectorCompiler
3137
{
@@ -57,6 +63,16 @@ class SelectorCompiler
5763
'only-child' => ['only-child'],
5864
'only-of-type' => ['only-of-type'],
5965
'empty' => ['empty'],
66+
'root' => ['root'],
67+
'link' => ['link'],
68+
'any-link' => ['link'],
69+
'visited' => ['never'],
70+
'hover' => ['never'],
71+
'active' => ['never'],
72+
'focus' => ['never'],
73+
'focus-within' => ['never'],
74+
'focus-visible' => ['never'],
75+
'target' => ['never'],
6076
];
6177

6278
/**
@@ -135,13 +151,15 @@ private function parseComplex($text, &$pos)
135151
$combinators = [];
136152
$specificity = [0, 0, 0];
137153
$universal = false;
154+
$never = false;
138155

139156
while (true) {
140157
$compound = $this->parseCompound($text, $pos, $specificity, $universal);
141158
if ($compound === null) {
142159
return null;
143160
}
144161
$compounds[] = $compound;
162+
$never = $never || in_array(['never'], $compound['pseudos'], true);
145163

146164
$space = $this->skipWhitespace($text, $pos);
147165
if ($pos >= $length || $text[$pos] === ',' || $text[$pos] === ')') {
@@ -164,6 +182,7 @@ private function parseComplex($text, &$pos)
164182
'combinators' => $combinators,
165183
'specificity' => $specificity,
166184
'universal' => $universal,
185+
'never' => $never,
167186
];
168187
}
169188

@@ -640,14 +659,19 @@ private function skipWhitespace($text, &$pos)
640659

641660
/**
642661
* Whether a type selector may name a tag. Which elements take part in the cascade is decided per tag, by
643-
* Mpdf::$allowedCSStags, as it is for the selectors the legacy parser reads
662+
* Mpdf::$allowedCSStags, as it is for the selectors the legacy parser reads. html is always allowed: the matcher
663+
* holds it as the parent of body
644664
*
645665
* @param string $tag Uppercased
646666
*
647667
* @return bool
648668
*/
649669
private function isAllowedTag($tag)
650670
{
671+
if ($tag === 'HTML') {
672+
return true;
673+
}
674+
651675
if ($this->allowedTagsSource !== $this->mpdf->allowedCSStags) {
652676
$this->allowedTagsSource = $this->mpdf->allowedCSStags;
653677
$this->allowedTags = array_fill_keys(explode('|', strtoupper($this->allowedTagsSource)), true);

0 commit comments

Comments
 (0)