Skip to content

Commit b491fdf

Browse files
jakejackson1claude
andcommitted
Honour !important in stylesheets and inline styles in cssMode standard (mpdf#1010)
Under the standard cascade, declarations marked !important apply after the inline style: those of the document's stylesheets by specificity and then position, then those of the inline style, then those of the default stylesheet. Each declaration block is split into normal and important declarations, normalised on their own, so a shorthand marked important expands into important longhands. @page, body and SVG class rules take an important declaration over a later one of the same selector. Legacy mode still reads the flag as nothing. In both modes the flag is taken out of the value whatever its spacing and case, so "margin: 5mm ! important" no longer sets margins to "!" and "important". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 14989d6 commit b491fdf

21 files changed

Lines changed: 1247 additions & 70 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ 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+
* **`!important` is honoured**, as in a browser, in standard mode. mPDF read a declaration marked `!important` as any other, so `p { color: green !important } #i { color: red }` drew `<p id="i">` red, and so did `style="color: red"` on a `<p>`. Now an important declaration beats every declaration that is not, the inline style included. Set `'cssMode' => \Mpdf\CssMode::LEGACY` to read the flag as nothing, as mPDF v7 did. [mpdf/mpdf#1010] [mpdf/mpdf#1707] [#532] [#638]
46+
* Important declarations apply after the inline style: those of the stylesheets by specificity and then order, then those of `style=""`, then those of the default stylesheet (`defaultCssFile`), as a browser's own important declarations beat a page's.
47+
* A shorthand marked `!important` makes every longhand it sets important, so `border: 1mm solid green !important` beats a `border-top-color` of a more specific rule or of a later declaration in the same block.
48+
* `@page` rules, `body` rules and the class rules SVG text looks up take an important declaration over a later one of the same selector that is not. An important declaration of a `body` rule beats `<body style>`.
4549

4650
New features
4751
------------
@@ -155,6 +159,7 @@ Bugfixes
155159
* Descendant rules naming a table, row or cell, such as `td img` or `td span`, matched nothing inside the cell. [#223] [#507]
156160
* A descendant rule with a part mPDF cannot parse was cut short at that part and applied to the element before it. Such rules are now dropped. [#519]
157161
* An inline `style` with `!important` drew no border for a `border` shorthand, dropped the bottom padding of a two-value `padding`, drew text at 0pt for a `font-size`, and ignored an image's `height` with a warning. The flag is now removed, as it is from a stylesheet. [mpdf/mpdf#1010] [mpdf/mpdf#1707] [#523] [#561]
162+
* A declaration whose flag had a space after the bang, such as `margin: 5mm ! important`, kept the flag in its value: that margin set the right and left margins to `!` and the bottom one to `important`, a `font-size` was lost, and a `border` drew nothing. The flag is now found whatever its spacing and case, in stylesheets and inline styles, in either `cssMode`. [#532] [#638]
158163
* Text styled with the `font` shorthand or `<font face>` came out as empty boxes when the family was not installed or had a space in its name, such as `font: 12pt Roboto` or `font: 16px "DejaVu Sans Mono"`. It was drawn in the first registered font, which is the emoji font in a full install. The family is now read as `font-family` reads it: a name is kept whole, the list is tried in order, and when mPDF knows none of it the text keeps the family it inherits. `font-family` itself also reads an unquoted name with spaces whole. [#552] [#560]
159164
* A descendant rule ending in `:lang()` or `[lang]`, such as `div :lang(fr)`, `div p:lang(fr)` or `table [lang=fr]`, never applied. It now applies in block content and in tables, and a regional language such as `fr-CA` falls back to the rule for `fr`, as the simple lang rules do. [#525] [#559]
160165
* A rule such as `td:nth-child(2):not(.x)` or `td:nth-child(2 of .x)` was applied to the second cell of every row, as if it were `td:nth-child(2)`. A rule with anything after an nth-child argument, or with an argument that is not a formula, is now dropped. [mpdf/mpdf#83] [#522] [#564]
@@ -792,6 +797,7 @@ These changes do not change output.
792797
[#526]: https://github.com/GravityPDF/mpdf/issues/526
793798
[#527]: https://github.com/GravityPDF/mpdf/issues/527
794799
[#528]: https://github.com/GravityPDF/mpdf/issues/528
800+
[#532]: https://github.com/GravityPDF/mpdf/issues/532
795801
[#533]: https://github.com/GravityPDF/mpdf/issues/533
796802
[#535]: https://github.com/GravityPDF/mpdf/issues/535
797803
[#536]: https://github.com/GravityPDF/mpdf/issues/536
@@ -844,3 +850,4 @@ These changes do not change output.
844850
[#633]: https://github.com/GravityPDF/mpdf/pull/633
845851
[#635]: https://github.com/GravityPDF/mpdf/pull/635
846852
[#634]: https://github.com/GravityPDF/mpdf/pull/634
853+
[#638]: https://github.com/GravityPDF/mpdf/pull/638

‎src/Css/CssMerger.php‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,10 @@ public function merge($inherit, $tag, $attr)
160160
/**
161161
* Merges an element's CSS as standard mode orders it, in layers, each over the one before: the inherited
162162
* values, the built-in defaults and the default stylesheet's rules, the presentational attributes as author rules
163-
* of zero specificity, the author rules, and the inline style. The rules of each stylesheet apply by specificity,
164-
* then in the order they were written.
163+
* of zero specificity, the author rules, and the inline style; then the !important declarations of the author
164+
* rules, of the inline style, and of the default stylesheet's rules. The rules of each stylesheet apply by
165+
* specificity, then in the order they were written. Each rule that reaches a table cell draws its borders over
166+
* those of its neighbours.
165167
*
166168
* @param string $inherit Inheritance context (BLOCK, INLINE, TABLE, TOPTABLE)
167169
* @param string $tag HTML tag name
@@ -189,45 +191,45 @@ private function mergeInCascadeOrder($inherit, $tag, array $attr)
189191

190192
$id = isset($attr['ID']) ? $attr['ID'] : '';
191193
$classes = $this->classesOf($attr);
194+
$dominance = $tag === 'TD' || $tag === 'TH' ? 9 : false;
192195

193196
$this->mergeInheritedBlockProperties($inherit, $tag);
194197

195198
$this->mergeDefaultCss($tag);
196-
$this->mergeMatchingRules($this->cssManager->getDefaultRules(), $tag, $id, $classes, $path);
199+
list($defaultRules, $importantDefaultRules) = $this->cssManager->getDefaultRules()->matchingDeclarations($tag, $id, $classes, $path);
200+
$this->mergeEach($defaultRules, $dominance);
197201

198202
$this->mergeInlineAttributes($tag, $attr);
199203
$this->mergeTableSpecificCss($tag, $attr);
200204

201205
if ($tag === 'BODY') {
202206
// Merged outside the document's elements, and written to by Mpdf::SetDefaultBodyCSS() and the like
203-
$body = isset($this->cssManager->CSS['BODY']) ? $this->cssManager->CSS['BODY'] : [];
204-
$this->setMergedCss($body, false);
207+
$important = $this->cssManager->getImportantCss();
208+
$importantDefault = $this->cssManager->getDefaultImportantCss();
209+
$rules = [isset($this->cssManager->CSS['BODY']) ? $this->cssManager->CSS['BODY'] : []];
210+
$importantRules = isset($important['BODY']) ? [$important['BODY']] : [];
211+
$importantDefaultRules = isset($importantDefault['BODY']) ? [$importantDefault['BODY']] : [];
205212
} else {
206-
$this->mergeMatchingRules($this->cssManager->getRules(), $tag, $id, $classes, $path);
213+
list($rules, $importantRules) = $this->cssManager->getRules()->matchingDeclarations($tag, $id, $classes, $path);
207214
}
215+
$this->mergeEach($rules, $dominance);
208216

209-
$this->mergeInlineStyle($tag, $attr);
217+
list($inline, $importantInline) = isset($attr['STYLE']) ? $this->inlineStyleParser->parseByImportance($attr['STYLE']) : [[], []];
218+
$this->mergeEach(array_merge([$inline], $importantRules, [$importantInline], $importantDefaultRules), $dominance);
210219

211220
return $this->cssProperties;
212221
}
213222

214223
/**
215-
* Merges the declarations of the rules in a rule set that an element matches, in the order they apply: by
216-
* specificity, then by their position in the stylesheets. Each rule that reaches a table cell draws its borders
217-
* over those of its neighbours
224+
* Merges sets of properties, each over those before it
218225
*
219-
* @param RuleSet $rules
220-
* @param string $tag HTML tag name, uppercased
221-
* @param string $id Uppercased, or empty for none
222-
* @param string[] $classes Uppercased
223-
* @param callable $path Gives the open elements from the document down to the element, or null for none
226+
* @param array[] $sets
227+
* @param int|false $dominance The border dominance each set's borders take in a table cell, or false outside one
224228
* @return void
225229
*/
226-
private function mergeMatchingRules(RuleSet $rules, $tag, $id, array $classes, callable $path)
230+
private function mergeEach(array $sets, $dominance)
227231
{
228-
$dominance = $tag === 'TD' || $tag === 'TH' ? 9 : false;
229-
230-
foreach ($rules->matchingDeclarations($tag, $id, $classes, $path) as $properties) {
232+
foreach ($sets as $properties) {
231233
$this->setMergedCss($properties, false, $dominance);
232234
}
233235
}

‎src/Css/CssParser.php‎

Lines changed: 69 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,12 @@ class CssParser
8888
*/
8989
private $css = [];
9090

91+
/**
92+
* @var array[] The properties the !important declarations of the rules in $css set, under the same keys. Only
93+
* standard mode keeps them apart
94+
*/
95+
private $importantCss = [];
96+
9197
/**
9298
* CSS for cascaded selectors.
9399
*
@@ -127,8 +133,8 @@ class CssParser
127133
private $nthChildFormulas = ['TR' => [], 'TD' => [], 'TH' => []];
128134

129135
/**
130-
* @var array[] The rules of the last CSS parsed for the matcher, each compiled: [compiled selector, declarations],
131-
* in the order they were written
136+
* @var array[] The rules of the last CSS parsed for the matcher, each compiled: [compiled selector, declarations,
137+
* !important declarations], in the order they were written
132138
*/
133139
private $compiledRules = [];
134140

@@ -160,6 +166,7 @@ public function __construct(
160166
public function parse($html)
161167
{
162168
$this->css = [];
169+
$this->importantCss = [];
163170
$this->cascadeCSS = [];
164171
$this->compiledRules = [];
165172

@@ -215,6 +222,17 @@ public function getCss()
215222
return $this->css;
216223
}
217224

225+
/**
226+
* The properties the !important declarations of the last CSS parsed set, under the keys getCss() uses. Legacy mode
227+
* reads those declarations as any other, into getCss(), and leaves this empty
228+
*
229+
* @return array[]
230+
*/
231+
public function getImportantCss()
232+
{
233+
return $this->importantCss;
234+
}
235+
218236
/**
219237
* @return array
220238
*/
@@ -226,7 +244,7 @@ public function getCascadeCss()
226244
/**
227245
* The rules of the last CSS parsed for the matcher, in standard mode. Legacy mode compiles none
228246
*
229-
* @return array[] Each [compiled selector, declarations], in the order they were written
247+
* @return array[] Each [compiled selector, declarations, !important declarations], in the order they were written
230248
*/
231249
public function getCompiledRules()
232250
{
@@ -299,14 +317,14 @@ private function processCssString($css)
299317
*/
300318
private function processRule($selectors, $declarations)
301319
{
302-
$classProperties = $this->parseCssProperties($declarations);
320+
list($classProperties, $important) = $this->parseCssPropertiesByImportance($declarations);
303321

304322
if (strpbrk($selectors, "\t\n\r\f\v") !== false) {
305323
$selectors = preg_replace(self::WHITESPACE, ' ', $selectors);
306324
}
307325

308326
foreach ($this->selectorCompiler->splitList($selectors) as $selector) {
309-
$this->processCssSelector($selector, $classProperties);
327+
$this->processCssSelector($selector, $classProperties, $important);
310328
}
311329
}
312330

@@ -315,9 +333,10 @@ private function processRule($selectors, $declarations)
315333
*
316334
* @param string $written Selector string, as written
317335
* @param array $classProperties CSS properties
336+
* @param array $important The properties its !important declarations set, which only standard mode reads apart
318337
* @return void
319338
*/
320-
private function processCssSelector($written, $classProperties)
339+
private function processCssSelector($written, $classProperties, array $important)
321340
{
322341
$selector = strtoupper($written);
323342

@@ -337,10 +356,8 @@ private function processCssSelector($written, $classProperties)
337356
$level = count($tags);
338357
if (trim($tags[0]) === '@PAGE') {
339358
$tag = $this->selectorParser->parsePageSelector($tags);
340-
if ($tag && isset($this->css[$tag])) {
341-
$this->css[$tag] = Arrays::uniqueRecursiveMerge($this->css[$tag], $classProperties);
342-
} elseif ($tag) {
343-
$this->css[$tag] = $classProperties;
359+
if ($tag) {
360+
$this->storeByKey($tag, $classProperties, $important);
344361
}
345362

346363
return;
@@ -352,11 +369,12 @@ private function processCssSelector($written, $classProperties)
352369
// Legacy mode applies simple rules from these keys, and standard mode keeps them for what reads
353370
// CssManager::$CSS directly: BODY, and SVG's classes
354371
if ($simple) {
355-
$this->storeSimpleRule($tag, $classProperties);
372+
$this->storeByKey($tag, $classProperties, $important);
373+
$this->indexStoredKey($tag);
356374
}
357375

358376
if ($this->mpdf->cssMode === CssMode::STANDARD) {
359-
$this->compileRule($written, $classProperties);
377+
$this->compileRule($written, $classProperties, $important);
360378

361379
return;
362380
}
@@ -382,21 +400,20 @@ private function processCssSelector($written, $classProperties)
382400
}
383401

384402
/**
385-
* Stores a rule whose selector is one compound the legacy parser reads, under its key
403+
* Stores a rule under its key: an @page rule, or one whose selector is one compound the legacy parser reads
386404
*
387-
* @param string $key A key SelectorParser::parseSimpleSelector() made, e.g. P or CLASS>>A
405+
* @param string $key A key SelectorParser made, e.g. P, CLASS>>A or @PAGE
388406
* @param array $classProperties
407+
* @param array $important The properties its !important declarations set
389408
* @return void
390409
*/
391-
private function storeSimpleRule($key, array $classProperties)
410+
private function storeByKey($key, array $classProperties, array $important)
392411
{
393-
if (isset($this->css[$key])) {
394-
$this->css[$key] = Arrays::uniqueRecursiveMerge($this->css[$key], $classProperties);
395-
} else {
396-
$this->css[$key] = $classProperties;
397-
}
412+
$this->css[$key] = Arrays::uniqueRecursiveMerge(isset($this->css[$key]) ? $this->css[$key] : [], $classProperties);
398413

399-
$this->indexStoredKey($key);
414+
if ($important) {
415+
$this->importantCss[$key] = Arrays::uniqueRecursiveMerge(isset($this->importantCss[$key]) ? $this->importantCss[$key] : [], $important);
416+
}
400417
}
401418

402419
/**
@@ -443,19 +460,20 @@ private function isLegacySelector(array $levels)
443460
*
444461
* @param string $selector As written
445462
* @param array $classProperties
463+
* @param array $important The properties its !important declarations set
446464
* @return void
447465
*/
448-
private function compileRule($selector, array $classProperties)
466+
private function compileRule($selector, array $classProperties, array $important)
449467
{
450-
if (!$classProperties) {
468+
if (!$classProperties && !$important) {
451469
return;
452470
}
453471

454472
$compiled = $this->selectorCompiler->compile($selector);
455473

456474
// The universal selector changes which elements existing documents style, so it waits for #530
457475
if ($compiled !== null && !$compiled['universal']) {
458-
$this->compiledRules[] = [$compiled, $classProperties];
476+
$this->compiledRules[] = [$compiled, $classProperties, $important];
459477
}
460478
}
461479

@@ -466,6 +484,32 @@ private function compileRule($selector, array $classProperties)
466484
* @return array Associative array of CSS properties
467485
*/
468486
public function parseCssProperties($rawStyles)
487+
{
488+
return $this->inlineStyleParser->parseDeclarations($this->declarationsOf($rawStyles));
489+
}
490+
491+
/**
492+
* The properties the normal declarations of a block set, and those its !important ones set. Legacy mode reads a
493+
* declaration marked !important as any other
494+
*
495+
* @param string $rawStyles The declarations of a block, with its comments removed
496+
* @return array[] [normal properties, important properties]
497+
*/
498+
private function parseCssPropertiesByImportance($rawStyles)
499+
{
500+
if ($this->mpdf->cssMode === CssMode::STANDARD) {
501+
return $this->inlineStyleParser->parseDeclarationsByImportance($this->declarationsOf($rawStyles));
502+
}
503+
504+
return [$this->parseCssProperties($rawStyles), []];
505+
}
506+
507+
/**
508+
* @param string $rawStyles The declarations of a block, with its comments removed
509+
* @return string[][] Each [name, value], with the whitespace in the value read as spaces and its data URI images
510+
* stored
511+
*/
512+
private function declarationsOf($rawStyles)
469513
{
470514
$declarations = $this->tokenizer->declarations($rawStyles);
471515
foreach ($declarations as &$declaration) {
@@ -479,7 +523,7 @@ public function parseCssProperties($rawStyles)
479523
}
480524
unset($declaration);
481525

482-
return $this->inlineStyleParser->parseDeclarations($declarations);
526+
return $declarations;
483527
}
484528

485529
/**

0 commit comments

Comments
 (0)