Skip to content

Commit 3c2f1fd

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 dce3ce4 commit 3c2f1fd

23 files changed

Lines changed: 1199 additions & 53 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Read this section before upgrading from upstream mPDF. Each entry says what chan
4242
* Class and id names still match whatever their case.
4343
* An author's `a { }` rule now reaches the links of the table of contents and the index too. Style `a.mpdf_toc_a` and `a.mpdf_index_link` to keep them plain.
4444
* In legacy mode, a rule whose selector mPDF v7 could not read is dropped: child and sibling combinators, structural pseudo-classes outside tables, attribute selectors other than `[lang]`, `:lang()` through an ancestor, descendant rules through inline ancestors, and `:not()`, `:is()` and `:where()`. The `font`, `border` and `background` shorthands leave the longhands they do not name, as mPDF v7 did. Fixes to how values and selectors are read apply in both modes. [#633]
45+
* **`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] [#PRNUM]
4546

4647
New features
4748
------------
@@ -114,6 +115,7 @@ New features
114115
* **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]
115116
* `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.
116117
* `:empty` matches as in browsers: an element holding white space is not empty. In the default mode mPDF's CSS reader turns each HTML comment into a space, so an element holding only a comment is not empty either. A table cell holding only white space is empty, as mPDF strips it.
118+
* **`: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] [#PRNUM]
117119

118120
Performance
119121
-----------
@@ -787,6 +789,7 @@ These changes do not change output.
787789
[#526]: https://github.com/GravityPDF/mpdf/issues/526
788790
[#527]: https://github.com/GravityPDF/mpdf/issues/527
789791
[#528]: https://github.com/GravityPDF/mpdf/issues/528
792+
[#529]: https://github.com/GravityPDF/mpdf/issues/529
790793
[#533]: https://github.com/GravityPDF/mpdf/issues/533
791794
[#535]: https://github.com/GravityPDF/mpdf/issues/535
792795
[#537]: https://github.com/GravityPDF/mpdf/issues/537
@@ -837,3 +840,4 @@ These changes do not change output.
837840
[#632]: https://github.com/GravityPDF/mpdf/issues/632
838841
[#633]: https://github.com/GravityPDF/mpdf/pull/633
839842
[#634]: https://github.com/GravityPDF/mpdf/pull/634
843+
[#PRNUM]: https://github.com/GravityPDF/mpdf/pull/PRNUM

‎src/Css/CssMerger.php‎

Lines changed: 43 additions & 1 deletion
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
@@ -57,6 +58,11 @@ class CssMerger
5758
*/
5859
private $borderMerger;
5960

61+
/**
62+
* @var SizeConverter
63+
*/
64+
private $sizeConverter;
65+
6066
/**
6167
* @var bool When true, state outside this object will be modified
6268
* @internal self::previewBlockCss() uses this property to look ahead without affecting state
@@ -70,7 +76,8 @@ public function __construct(
7076
SelectorParser $selectorParser,
7177
InlinePropertyConverter $inlinePropertyConverter,
7278
ColorConverter $colorConverter,
73-
BorderMerger $borderMerger
79+
BorderMerger $borderMerger,
80+
SizeConverter $sizeConverter
7481
) {
7582
$this->mpdf = $mpdf;
7683
$this->normalizeProperties = $normalizeProperties;
@@ -79,6 +86,7 @@ public function __construct(
7986
$this->inlinePropertyConverter = $inlinePropertyConverter;
8087
$this->colorConverter = $colorConverter;
8188
$this->borderMerger = $borderMerger;
89+
$this->sizeConverter = $sizeConverter;
8290
}
8391

8492
/**
@@ -202,6 +210,7 @@ private function mergeInCascadeOrder($inherit, $tag, array $attr)
202210
// Merged outside the document's elements, and written to by Mpdf::SetDefaultBodyCSS() and the like
203211
$body = isset($this->cssManager->CSS['BODY']) ? $this->cssManager->CSS['BODY'] : [];
204212
$this->setMergedCss($body, false);
213+
$this->mergeDocumentRules();
205214
} else {
206215
$this->mergeMatchingRules($this->cssManager->getRules(), $tag, $id, $classes, $path);
207216
}
@@ -211,6 +220,39 @@ private function mergeInCascadeOrder($inherit, $tag, array $attr)
211220
return $this->cssProperties;
212221
}
213222

223+
/**
224+
* Merges html's rules into body's CSS, and body's own rules again over them. mPDF has no html element: the
225+
* document's frame stands for body, and html is matched as its parent, so html's declarations reach the text as a
226+
* parent's would, and lose to body's. Both win over what SetDefaultBodyCSS() and the like set.
227+
*
228+
* html's font size, read against the default font size, is the root's, which rem and body's own size are read
229+
* against
230+
*
231+
* @return void
232+
*/
233+
private function mergeDocumentRules()
234+
{
235+
$rules = $this->cssManager->getRules();
236+
$path = $this->mpdf->getDocumentPath();
237+
$initial = $this->mpdf->initial_font_size;
238+
$this->mpdf->root_font_size = $initial;
239+
240+
foreach ($rules->documentDeclarations(true, $path) as $properties) {
241+
if (isset($properties['FONT-SIZE'])) {
242+
$size = $this->sizeConverter->convertFontSize($properties['FONT-SIZE'], $initial / Mpdf::SCALE, $initial);
243+
if ($size !== null) {
244+
$this->mpdf->root_font_size = $size;
245+
$properties['FONT-SIZE'] = $size . 'pt';
246+
}
247+
}
248+
$this->setMergedCss($properties, false);
249+
}
250+
251+
foreach ($rules->documentDeclarations(false, $path) as $properties) {
252+
$this->setMergedCss($properties, false);
253+
}
254+
}
255+
214256
/**
215257
* Merges the declarations of the rules in a rule set that an element matches, in the order they apply: by
216258
* specificity, then by their position in the stylesheets. Each rule that reaches a table cell draws its borders

‎src/Css/CssParser.php‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -287,13 +287,6 @@ private function processCssSelector($written, $classProperties)
287287
{
288288
$selector = strtoupper($written);
289289

290-
// store classes in an index for faster lookups
291-
if (strpos($selector, '.') !== false && preg_match_all('/\.([a-zA-Z0-9_\-]+)/', $selector, $matches)) {
292-
foreach ($matches[1] as $className) {
293-
$this->usedClassNames[$className] = true;
294-
}
295-
}
296-
297290
// Close up each nth-child argument, e.g. (2N + 1), so the selector still splits into its parts on whitespace
298291
$selector = preg_replace_callback('/NTH-CHILD\(([^)]*)\)/', function ($m) {
299292
return 'NTH-CHILD(' . preg_replace('/\s+/', '', $m[1]) . ')';
@@ -366,8 +359,8 @@ private function storeSimpleRule($key, array $classProperties)
366359
}
367360

368361
/**
369-
* Record what the merger needs to know about the key of one compound selector of a stored rule: how many classes
370-
* it names, and its nth-child formula.
362+
* Record what the merger needs to know about the key of one compound selector of a stored rule: the classes it
363+
* names and how many, and its nth-child formula. A rule that is not stored, as one naming :hover, records nothing.
371364
*
372365
* @param string $key A key SelectorParser::parseSimpleSelector() made, e.g. P>>CLASS>>A.B or TD>>SELECTORNTHCHILD>>2N+1
373366
* @return void
@@ -377,6 +370,11 @@ private function indexStoredKey($key)
377370
$classes = strpos($key, 'CLASS>>');
378371
if ($classes !== false) {
379372
$this->maxClassDepth = max($this->maxClassDepth, substr_count($key, '.', $classes) + 1);
373+
374+
preg_match_all('/\.([a-zA-Z0-9_\-]+)/', '.' . substr($key, $classes + 7), $matches);
375+
foreach ($matches[1] as $className) {
376+
$this->usedClassNames[$className] = true;
377+
}
380378
}
381379

382380
if (preg_match('/^(TR|TD|TH)>>SELECTORNTHCHILD>>(.*)$/', $key, $m) && !isset($this->nthChildFormulas[$m[1]][$key])) {
@@ -420,7 +418,7 @@ private function compileRule($selector, array $classProperties)
420418
$compiled = $this->selectorCompiler->compile($selector);
421419

422420
// The universal selector changes which elements existing documents style, so it waits for #530
423-
if ($compiled !== null && !$compiled['universal']) {
421+
if ($compiled !== null && !$compiled['universal'] && !$compiled['never']) {
424422
$this->compiledRules[] = [$compiled, $classProperties];
425423
}
426424
}

‎src/Css/RuleSet.php‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,37 @@ public function matchingDeclarations($tag, $id, array $classes, callable $path)
102102
}
103103
}
104104

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

133164
/**
165+
* Files a rule under its id, class or tag. With none, :root files it under html, and :link under the tags it
166+
* matches
167+
*
134168
* @param array $index
135169
* @param array $subject The rightmost compound of a rule's selector
136170
* @param int $position The rule's position
@@ -143,6 +177,11 @@ private static function file(array &$index, array $subject, $position)
143177
$index['class'][$subject['classes'][0]][] = $position;
144178
} elseif ($subject['tag'] !== null) {
145179
$index['tag'][$subject['tag']][] = $position;
180+
} elseif (in_array(['root'], $subject['pseudos'], true)) {
181+
$index['tag']['HTML'][] = $position;
182+
} elseif (in_array(['link'], $subject['pseudos'], true)) {
183+
$index['tag']['A'][] = $position;
184+
$index['tag']['AREA'][] = $position;
146185
} else {
147186
$index['any'][] = $position;
148187
}
@@ -213,11 +252,11 @@ private static function requiredAncestors(array $selector)
213252
* @param array[] $path The open elements from the document down to the element, with the element last
214253
*
215254
* @return array<string, true> The keys requiredAncestors() gives for the ids, classes and tags of the element's
216-
* ancestors, the document's frame being body
255+
* ancestors, the document's frame being body, with html above it
217256
*/
218257
private static function ancestorsOf(array $path)
219258
{
220-
$keys = ['T' . 'BODY' => true]; // the document's frame
259+
$keys = ['T' . 'HTML' => true, 'T' . 'BODY' => true]; // html, and the document's frame
221260
for ($depth = count($path) - 2; $depth > 0; $depth--) {
222261
$keys['T' . $path[$depth]['tag']] = true;
223262
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)