Skip to content

Commit 4295123

Browse files
jakejackson1claude
andauthored
Unwrap @supports and @layer and remove other at-rules whole so the rule after them still applies (#566)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4e0b345 commit 4295123

10 files changed

Lines changed: 612 additions & 44 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ Bugfixes
135135
* `border-color: rgb(255, 0, 0)` or `cmyk(0, 100, 0, 0)`, with spaces after the commas, drew black.
136136
* A declaration mPDF cannot read replaced the value before it. A `calc()`, `min()`, `max()`, `clamp()` or `var()` length became 0, so `margin: calc(…)` removed the default margins, and a colour mPDF does not know, or one written with `var()`, drew the text black. Such a declaration is now dropped, as a browser drops it, so the earlier declaration, the default or the inherited value applies. [#552] [#565]
137137
* `vw`, `vh`, `vmin`, `vmax`, `Q` and `ch` were read as pixels, `+5mm` and `1e+1mm` as 0, and `1,5mm` as 1mm. The units are now resolved against the page and the font size, the numbers are read, and `1,5mm` is dropped. [#552] [#565]
138+
* The rule after an `@supports`, `@layer`, `@keyframes`, `@container` or other block at-rule was lost, and so were the rules inside `@supports` and `@layer`. The rule after `@charset`, `@namespace` or `@import` was lost too. `@supports` and `@layer` blocks are now unwrapped as `@media` blocks are, except `@supports not`, and other at-rules are removed whole. [#524] [#566]
138139
* A percentage `width`, `min-width` or `max-width` on an image in a table cell was resolved against the block around the table, not the cell. In a 60mm cell, `max-width: 20%` came out as 36mm. [#223] [#505]
139140
* An `@page :left` or `@page :right` rule was ignored unless the style sheet also had a plain `@page` rule. With one, the margins of a `:right` rule were applied to left pages too. [#555] [#556]
140141
* When a later `WriteHTML()` call turned the document right to left, the text on the page already started was set between the swapped side margins. That page now keeps its margins, and the swap starts with the next page. [#554] [#558]
@@ -720,6 +721,7 @@ These changes do not change output.
720721
[#519]: https://github.com/GravityPDF/mpdf/pull/519
721722
[#522]: https://github.com/GravityPDF/mpdf/issues/522
722723
[#523]: https://github.com/GravityPDF/mpdf/issues/523
724+
[#524]: https://github.com/GravityPDF/mpdf/issues/524
723725
[#549]: https://github.com/GravityPDF/mpdf/pull/549
724726
[#561]: https://github.com/GravityPDF/mpdf/pull/561
725727
[#525]: https://github.com/GravityPDF/mpdf/issues/525
@@ -738,4 +740,5 @@ These changes do not change output.
738740
[#564]: https://github.com/GravityPDF/mpdf/pull/564
739741
[#563]: https://github.com/GravityPDF/mpdf/pull/563
740742
[#565]: https://github.com/GravityPDF/mpdf/pull/565
743+
[#566]: https://github.com/GravityPDF/mpdf/pull/566
741744
[#615]: https://github.com/GravityPDF/mpdf/pull/615

‎src/Css/AtRuleProcessor.php‎

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
<?php
2+
3+
namespace Mpdf\Css;
4+
5+
/**
6+
* Settles the at-rules in a stylesheet before it is split into rules at each brace.
7+
*
8+
* The rules in a matching @media block, and in @supports and @layer blocks, are unwrapped into the stylesheet. An
9+
* @supports condition is taken to pass, as its rules are unwrapped, so an @supports not block, the fallback for
10+
* engines without a feature, is removed. @page rules are kept, less any margin boxes nested in them. Every other
11+
* at-rule is removed whole, with its block if it has one: splitting at each brace would otherwise end the at-rule at
12+
* its first inner brace and take the rest of it as the start of the next rule.
13+
*/
14+
class AtRuleProcessor
15+
{
16+
17+
/**
18+
* @var MediaQueryProcessor
19+
*/
20+
private $mediaQueryProcessor;
21+
22+
/**
23+
* @param MediaQueryProcessor $mediaQueryProcessor
24+
*/
25+
public function __construct(MediaQueryProcessor $mediaQueryProcessor)
26+
{
27+
$this->mediaQueryProcessor = $mediaQueryProcessor;
28+
}
29+
30+
/**
31+
* Unwrap, keep or remove each at-rule in a list of rules, copying the other rules as they are
32+
*
33+
* @param string $css A stylesheet with its comments removed
34+
* @return string The stylesheet with only plain rules and @page rules left
35+
*/
36+
public function process($css)
37+
{
38+
if (strpos($css, '@') === false) {
39+
return $css;
40+
}
41+
42+
$processed = '';
43+
$length = strlen($css);
44+
$pos = 0;
45+
46+
while ($pos < $length) {
47+
$at = $this->find($css, $pos, '@');
48+
if ($at >= $length || $css[$at] === '}') {
49+
$processed .= substr($css, $pos, $at + 1 - $pos);
50+
$pos = $at + 1;
51+
continue;
52+
}
53+
54+
$processed .= substr($css, $pos, $at - $pos) . ' ';
55+
list($name, $prelude, $body, $end) = $this->readAtRule($css, $at);
56+
if ($body !== null) {
57+
$processed .= $this->processBlock($name, $prelude, $body) . ' ';
58+
}
59+
60+
$pos = $end + 1;
61+
}
62+
63+
return $processed;
64+
}
65+
66+
/**
67+
* What a block at-rule leaves in the stylesheet
68+
*
69+
* @param string $name The at-rule's name in lower case, without the @
70+
* @param string $prelude What comes between the name and the block
71+
* @param string $body What is inside the block
72+
* @return string
73+
*/
74+
private function processBlock($name, $prelude, $body)
75+
{
76+
switch ($name) {
77+
case 'media':
78+
return $this->mediaQueryProcessor->matches($prelude) ? $this->process($body) : '';
79+
80+
case 'supports':
81+
return preg_match('/^not\b/i', $prelude) ? '' : $this->process($body);
82+
83+
case 'layer':
84+
return $this->process($body);
85+
86+
case 'page':
87+
return '@page ' . $prelude . ' {' . $this->removeNestedAtRules($body) . '}';
88+
}
89+
90+
return '';
91+
}
92+
93+
/**
94+
* Remove the at-rules from a block of declarations, such as the margin boxes in an @page rule
95+
*
96+
* @param string $declarations
97+
* @return string
98+
*/
99+
private function removeNestedAtRules($declarations)
100+
{
101+
if (strpos($declarations, '@') === false) {
102+
return $declarations;
103+
}
104+
105+
$length = strlen($declarations);
106+
$kept = '';
107+
$pos = 0;
108+
109+
while ($pos < $length) {
110+
$pos += strspn($declarations, " \t\n\r\f", $pos);
111+
if ($pos >= $length) {
112+
break;
113+
}
114+
115+
if ($declarations[$pos] === '@') {
116+
list(, , , $end) = $this->readAtRule($declarations, $pos);
117+
} else {
118+
$end = $this->find($declarations, $pos, ';');
119+
$kept .= ' ' . substr($declarations, $pos, $end + 1 - $pos);
120+
}
121+
122+
$pos = $end + 1;
123+
}
124+
125+
return $kept;
126+
}
127+
128+
/**
129+
* Read the at-rule starting at $at
130+
*
131+
* @param string $css
132+
* @param int $at The position of the @
133+
* @return array The name in lower case, the prelude, and the block's content or null for a statement at-rule,
134+
* then the position of the semicolon or brace that ends it
135+
*/
136+
private function readAtRule($css, $at)
137+
{
138+
$open = $this->find($css, $at, ';{');
139+
if ($open >= strlen($css) || $css[$open] !== '{') {
140+
return [null, null, null, $open];
141+
}
142+
143+
$close = $this->find($css, $open + 1, '');
144+
preg_match('/^@([-\w]*)(.*)$/s', substr($css, $at, $open - $at), $m);
145+
146+
return [strtolower($m[1]), trim($m[2]), substr($css, $open + 1, $close - $open - 1), $close];
147+
}
148+
149+
/**
150+
* The position of the first of $chars at or after $pos that is outside any string or nested block
151+
*
152+
* A closing brace that is not nested in the search ends it as well, since it closes the block being searched. The
153+
* length of the stylesheet is returned if neither is found.
154+
*
155+
* @param string $css
156+
* @param int $pos
157+
* @param string $chars
158+
* @return int
159+
*/
160+
private function find($css, $pos, $chars)
161+
{
162+
$length = strlen($css);
163+
$stops = $chars . '{}"\'\\';
164+
$depth = 0;
165+
166+
while ($pos < $length) {
167+
$pos += strcspn($css, $stops, $pos);
168+
if ($pos >= $length) {
169+
break;
170+
}
171+
172+
$char = $css[$pos];
173+
if ($depth === 0 && ($char === '}' || strpos($chars, $char) !== false)) {
174+
return $pos;
175+
}
176+
177+
if ($char === '"' || $char === '\'') {
178+
$pos = $this->endOfString($css, $pos);
179+
} elseif ($char === '\\') {
180+
$pos++;
181+
} elseif ($char === '{') {
182+
$depth++;
183+
} elseif ($char === '}') {
184+
$depth--;
185+
}
186+
187+
$pos++;
188+
}
189+
190+
return $length;
191+
}
192+
193+
/**
194+
* The position of the quote that closes the string opening at $pos, or of the line break or end of the stylesheet
195+
* that ends it unclosed
196+
*
197+
* @param string $css
198+
* @param int $pos
199+
* @return int
200+
*/
201+
private function endOfString($css, $pos)
202+
{
203+
$length = strlen($css);
204+
$quote = $css[$pos];
205+
206+
while (++$pos < $length) {
207+
$pos += strcspn($css, $quote . "\\\n\r\f", $pos);
208+
if ($pos >= $length || $css[$pos] !== '\\') {
209+
return $pos;
210+
}
211+
212+
$pos++;
213+
}
214+
215+
return $length;
216+
}
217+
}

‎src/Css/CssParser.php‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ class CssParser
2727
*/
2828
private $mediaQueryProcessor;
2929

30+
/**
31+
* @var AtRuleProcessor
32+
*/
33+
private $atRuleProcessor;
34+
3035
/**
3136
* @var CommentParser
3237
*/
@@ -114,6 +119,7 @@ public function __construct(
114119
$this->normalizeProperties = new NormalizeProperties($mpdf, $sizeConverter, $colorConverter);
115120
$this->cssLoader = new CssLoader($mpdf, $assetFetcher, $cache);
116121
$this->mediaQueryProcessor = new MediaQueryProcessor($mpdf);
122+
$this->atRuleProcessor = new AtRuleProcessor($this->mediaQueryProcessor);
117123
$this->commentParser = new CommentParser();
118124
$this->inlineStyleParser = new InlineStyleParser($this->normalizeProperties);
119125
$this->selectorParser = new SelectorParser($mpdf);
@@ -164,10 +170,10 @@ public function parse($html)
164170
}
165171

166172
$css = preg_replace('|/\*.*?\*/|s', ' ', $css);
173+
$css = preg_replace('/(<\!\-\-|\-\->)/s', ' ', $css);
174+
$css = $this->atRuleProcessor->process($css);
167175
$css = preg_replace('/[\s\n\r\t\f]/s', ' ', $css);
168-
$css = $this->mediaQueryProcessor->processMediaQueries($css);
169176
$css = $this->cssLoader->processDataUriImages($css);
170-
$css = preg_replace('/(<\!\-\-|\-\->)/s', ' ', $css);
171177
$css = $this->inlineStyleParser->processUrlsInCss($css);
172178

173179
$this->processCssString($css);

‎src/Css/MediaQueryProcessor.php‎

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -29,38 +29,22 @@ public function filterByMediaQuery($html, $pattern)
2929
{
3030
preg_match_all($pattern, $html, $m);
3131
foreach ($m[0] as $i => $url) {
32-
if (!$this->mpdf->CSSselectMedia || !preg_match('/(' . trim($this->mpdf->CSSselectMedia) . '|all)/i', $m[1][$i])) {
32+
// Unlike an @media block, a <style> or <link> for any medium is left out when CSSselectMedia names none
33+
if (!$this->mpdf->CSSselectMedia || !$this->matches($m[1][$i])) {
3334
$html = str_replace($m[0][$i], '', $html);
3435
}
3536
}
3637
return $html;
3738
}
3839

3940
/**
40-
* Process @media queries in CSS.
41+
* Whether a media query list applies to the medium CSSselectMedia names. Every list applies when it names none.
4142
*
42-
* Filters or unwraps @media blocks based on configured media type.
43-
* If media doesn't match CSSselectMedia, the entire block is removed.
44-
* If it matches, the contents are unwrapped.
45-
*
46-
* @param string $cssStr CSS string potentially containing @media rules
47-
* @return string CSS string with media queries processed
43+
* @param string $mediaQueryList
44+
* @return bool
4845
*/
49-
public function processMediaQueries($cssStr)
46+
public function matches($mediaQueryList)
5047
{
51-
if (!preg_match('/@media/', $cssStr)) {
52-
return $cssStr;
53-
}
54-
55-
preg_match_all('/@media(.*?)\{(([^\{\}]*\{[^\{\}]*\})+)\s*\}/is', $cssStr, $m);
56-
foreach ($m[0] as $i => $value) {
57-
if ($this->mpdf->CSSselectMedia && !preg_match('/(' . trim($this->mpdf->CSSselectMedia) . '|all)/i', $m[1][$i])) {
58-
$cssStr = str_replace($m[0][$i], '', $cssStr);
59-
} else {
60-
$cssStr = str_replace($m[0][$i], ' ' . $m[2][$i] . ' ', $cssStr);
61-
}
62-
}
63-
64-
return $cssStr;
48+
return !$this->mpdf->CSSselectMedia || preg_match('/(' . trim($this->mpdf->CSSselectMedia) . '|all)/i', $mediaQueryList) === 1;
6549
}
6650
}

0 commit comments

Comments
 (0)