Skip to content

Commit d933def

Browse files
jakejackson1claude
andcommitted
Match @media and @import media queries as before under cssMode legacy
In legacy mode MediaQueryProcessor::matches() applies a media query list when it contains the medium CSSselectMedia names, or all, anywhere, as it did before #575. That covers @media blocks and the media attributes of <style> and <link>. @import loads any URL ending in .css, whatever follows it, url() before quoted strings, and in a loaded stylesheet only url(). In both modes an @import is read only from <style> blocks and loaded stylesheets, not from the body text, and only among a stylesheet's own rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 14989d6 commit d933def

11 files changed

Lines changed: 459 additions & 178 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -166,8 +166,8 @@ Bugfixes
166166
* `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]
167167
* `line-height: 0` gave lines a normal height. Lines now have no height, as in a browser. A line height well below the font size, such as `0.5` or `1mm`, was stretched down to the baseline; it is now kept. A negative `line-height`, which shrank lines to odd heights, is now ignored. [#552] [#567]
168168
* 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]
169-
* `@media` was matched by looking for the word `print`, so `@media not print` applied, `orientation` was ignored and `min-width` never matched. Media queries are now evaluated for the print medium against the page current when the stylesheet is read: media types with `not` and `only`; `and`, `or` and `not` conditions; and `width`, `height` and `orientation`, with `min-`/`max-` prefixes and range syntax such as `(width >= 600px)`. An A4 page is about 794px wide, so `@media (min-width: 768px)` rules now apply to it. [#552] [#575]
170-
* `@import` ignored its media list, and did not load a URL that does not end in `.css`, such as a Google Fonts stylesheet. [#552] [#575]
169+
* `@media` was matched by looking for the word `print`, so `@media not print` applied, `orientation` was ignored and `min-width` never matched. Media queries are now evaluated for the print medium against the page current when the stylesheet is read: media types with `not` and `only`; `and`, `or` and `not` conditions; and `width`, `height` and `orientation`, with `min-`/`max-` prefixes and range syntax such as `(width >= 600px)`. An A4 page is about 794px wide, so `@media (min-width: 768px)` rules now apply to it. Set `'cssMode' => \Mpdf\CssMode::LEGACY` to keep matching by the word `print` or `all`. [#552] [#575] [#643]
170+
* `@import` ignored its media list, and did not load a URL that does not end in `.css`, such as a Google Fonts stylesheet. Legacy mode loads them as before, except that in either mode an `@import` is read only from `<style>` blocks and stylesheets, not from the body text. [#552] [#575] [#643]
171171
* A brace, semicolon or comment marker inside a quoted string, an unquoted `url()` or an escape broke the stylesheet around it. `q { quotes: "}" }` lost the rule after it, `font-family: 'a;color:red'` set the colour, a `/*` in one string and a `*/` in a later one removed every rule between them, and `@import url(…?family=Inter:wght@300;400)` lost the rule after it. A rule or at-rule nested in a block, as CSS nesting writes them, lost the rest of the block and the rule after it. Stylesheets are now split by a tokenizer that reads strings, `url()`, escapes and comments as CSS does, in either `cssMode`. A rule or at-rule nested in a block is left out, and the declarations after it apply. [#536] [#635]
172172
* A string left open ends at the line break, as in CSS. A block or comment left open ends with its `<style>` or stylesheet file instead of running into the next one.
173173
* A byte order mark at the start of a stylesheet, as `WriteHTML(file_get_contents('style.css'), HTMLParserMode::HEADER_CSS)` passes one on, no longer spoils the first rule.
@@ -844,3 +844,4 @@ These changes do not change output.
844844
[#633]: https://github.com/GravityPDF/mpdf/pull/633
845845
[#635]: https://github.com/GravityPDF/mpdf/pull/635
846846
[#634]: https://github.com/GravityPDF/mpdf/pull/634
847+
[#643]: https://github.com/GravityPDF/mpdf/pull/643

‎src/Css/CssLoader.php‎

Lines changed: 47 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Mpdf\AssetFetcher;
66
use Mpdf\Cache;
7+
use Mpdf\CssMode;
78
use Mpdf\Exception\AssetFetchingException;
89
use Mpdf\Mpdf;
910
use Mpdf\MpdfException;
@@ -99,27 +100,37 @@ public function extractExternalStylesheetUrls($html)
99100
}
100101

101102
preg_match_all('/<style.*?>(.*?)<\/style>/si', $html, $styles);
102-
foreach ($styles[1] as $css) {
103-
$cssUrls = array_merge($cssUrls, $this->extractImportUrls($css));
104-
}
105103

106-
return $cssUrls;
104+
return array_merge($cssUrls, $this->extractImportUrls($styles[1], true));
107105
}
108106

109107
/**
110-
* The URLs the @import rules in $css load, less those whose media query list does not match
108+
* The URLs the @import rules in the stylesheets load, less those whose media query list does not match
111109
*
112-
* Only an @import among the stylesheet's own rules is read, not one in a comment, a string or a block. A layer()
110+
* Only an @import among a stylesheet's own rules is read, not one in a comment, a string or a block. A layer()
113111
* before the media query list is ignored. A supports() condition is taken to pass, as the rules in an @supports
114112
* block are unwrapped, so one that starts with not fails.
115113
*
116-
* @param string $css
114+
* @param string[] $stylesheets
115+
* @param bool $inHtml Whether the stylesheets are the document's <style> blocks rather than one it loads, which
116+
* only legacy mode reads
117117
* @return string[]
118118
*/
119-
private function extractImportUrls($css)
119+
private function extractImportUrls(array $stylesheets, $inHtml)
120120
{
121-
if (stripos($css, '@import') === false) {
122-
return [];
121+
$preludes = [];
122+
foreach ($stylesheets as $css) {
123+
if (stripos($css, '@import') !== false) {
124+
foreach ($this->tokenizer->rules($this->tokenizer->removeComments($css)) as $rule) {
125+
if ($rule[0] === 'import' && $rule[2] === null) {
126+
$preludes[] = $rule[1];
127+
}
128+
}
129+
}
130+
}
131+
132+
if ($this->mpdf->cssMode === CssMode::LEGACY) {
133+
return $this->legacyImportUrls($preludes, $inHtml);
123134
}
124135

125136
$url = '(?|url\(\s*"([^"]*)"\s*\)|url\(\s*\'([^\']*)\'\s*\)|url\(\s*([^\s"\')]*)\s*\)|"([^"]*)"|\'([^\']*)\')';
@@ -128,9 +139,8 @@ private function extractImportUrls($css)
128139
$pattern = '/^' . $url . $layer . $supports . '(.*)$/is';
129140

130141
$urls = [];
131-
foreach ($this->tokenizer->rules($this->tokenizer->removeComments($css)) as $rule) {
132-
if ($rule[0] === 'import' && $rule[2] === null
133-
&& preg_match($pattern, $rule[1], $import)
142+
foreach ($preludes as $prelude) {
143+
if (preg_match($pattern, $prelude, $import)
134144
&& $import[1] !== '' && $import[2] === '' && $this->mediaQueryProcessor->matches($import[3])
135145
) {
136146
$urls[] = $import[1];
@@ -140,6 +150,29 @@ private function extractImportUrls($css)
140150
return $urls;
141151
}
142152

153+
/**
154+
* The URLs @import rules load in cssMode legacy, as mPDF v7 read them: any URL of a .css file, whatever follows
155+
* it. Those in url() come first, then, in <style> blocks only, those written as strings
156+
*
157+
* @param string[] $preludes
158+
* @param bool $inHtml
159+
* @return string[]
160+
*/
161+
private function legacyImportUrls(array $preludes, $inHtml)
162+
{
163+
$urls = [];
164+
$strings = [];
165+
foreach ($preludes as $prelude) {
166+
if (preg_match('/^url\([\'"]?(\S*?\.css(\?[^\s\'"]+)?)[\'"]?\)/i', $prelude, $m)) {
167+
$urls[] = $m[1];
168+
} elseif ($inHtml && preg_match('/^(?!url)[\'"]?(\S*?\.css(\?[^\s\'"]+)?)/i', $prelude, $m)) {
169+
$strings[] = $m[1];
170+
}
171+
}
172+
173+
return array_merge($urls, $strings);
174+
}
175+
143176
/**
144177
* Locate embedded @import stylesheets in other stylesheets and fix url paths
145178
* (including background-images) relative to stylesheet
@@ -153,7 +186,7 @@ private function extractImportUrls($css)
153186
public function processExternalCssImports($stylesheetCss, $path, &$externalCss, &$externalCssCount)
154187
{
155188
$cssBasePath = preg_replace('/\/[^\/]*$/', '', $path) . '/';
156-
foreach ($this->extractImportUrls($stylesheetCss) as $cxtembedded) {
189+
foreach ($this->extractImportUrls([$stylesheetCss], false) as $cxtembedded) {
157190
// path is relative to original stylesheet!!
158191
$externalCss[] = Path::relativeToAbsolutePath($cxtembedded, $cssBasePath);
159192
$externalCssCount++;

‎src/Css/MediaQueryProcessor.php‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Mpdf\Css;
44

5+
use Mpdf\CssMode;
56
use Mpdf\Mpdf;
67
use Mpdf\SizeConverter;
78

@@ -65,11 +66,17 @@ public function filterByMediaQuery($html, $pattern)
6566
* Whether a media query list applies to the medium CSSselectMedia names. Every list applies when it names none, and
6667
* an empty list always applies.
6768
*
69+
* In cssMode legacy a list applies when it contains that medium's name or all anywhere, as mPDF v7 read it.
70+
*
6871
* @param string $mediaQueryList
6972
* @return bool
7073
*/
7174
public function matches($mediaQueryList)
7275
{
76+
if ($this->mpdf->cssMode === CssMode::LEGACY) {
77+
return !$this->mpdf->CSSselectMedia || preg_match('/(' . trim($this->mpdf->CSSselectMedia) . '|all)/i', $mediaQueryList) === 1;
78+
}
79+
7380
$mediaQueryList = strtolower(trim($mediaQueryList));
7481
if (!$this->mpdf->CSSselectMedia || $mediaQueryList === '') {
7582
return true;

‎tests/Mpdf/Css/CssLoaderTest.php‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Mpdf\AssetFetcher;
66
use Mpdf\Cache;
7+
use Mpdf\CssMode;
78
use Mpdf\Mpdf;
89
use Mpdf\SizeConverter;
910
use Psr\Log\NullLogger;
@@ -109,9 +110,37 @@ public function testExtractExternalStylesheetUrlsMatchesEachImportsMediaQueryLis
109110
);
110111
}
111112

113+
/**
114+
* In cssMode legacy an @import in a <style> block is loaded when its URL ends in .css, whatever follows it, with
115+
* those written as url() first. One in body text is not
116+
*/
117+
public function testExtractExternalStylesheetUrlsLoadsEachCssFileInLegacyMode()
118+
{
119+
$this->mpdf->cssMode = CssMode::LEGACY;
120+
$html = '<style>
121+
@import url(screen.css) screen;
122+
@import url("print.css") print;
123+
@import \'wide.css\' (min-width: 768px);
124+
@import "narrow.css" (max-width: 600px);
125+
@import url(https://fonts.googleapis.com/css2?family=Roboto&display=swap);
126+
@import url(/theme) layer(base) supports(display: grid) print;
127+
@import url(layered.css) layer screen;
128+
@import url(fallback.css) supports(not (display: grid));
129+
@import url(versioned.css?v=2) print;
130+
@import url( spaced.css );
131+
</style>
132+
<style>@import "second.css"; @import url(\'third.css\');</style>
133+
<p>@import "text.css";</p>';
134+
135+
$this->assertSame(
136+
['screen.css', 'print.css', 'layered.css', 'fallback.css', 'versioned.css?v=2', 'third.css', 'wide.css', 'narrow.css', 'second.css'],
137+
$this->cssLoader->extractExternalStylesheetUrls($html)
138+
);
139+
}
140+
112141
/**
113142
* Only an @import among a stylesheet's rules is loaded: not one in a comment, a string or a block, and not one
114-
* after a block left open
143+
* after a block left open. The same holds in cssMode legacy, which does not load the URL without .css
115144
*/
116145
public function testExtractExternalStylesheetUrlsReadsOnlyImportRules()
117146
{
@@ -129,6 +158,9 @@ public function testExtractExternalStylesheetUrlsReadsOnlyImportRules()
129158
['https://fonts.example/css2?family=Inter:wght@300;400&display=swap', 'after.css', 'next.css'],
130159
$this->cssLoader->extractExternalStylesheetUrls($html)
131160
);
161+
162+
$this->mpdf->cssMode = CssMode::LEGACY;
163+
$this->assertSame(['after.css', 'next.css'], $this->cssLoader->extractExternalStylesheetUrls($html));
132164
}
133165

134166
/**
@@ -170,6 +202,27 @@ public function testProcessExternalCssImportsQueuesImportsThatMatch()
170202
$this->assertSame(2, $count);
171203
}
172204

205+
/**
206+
* In cssMode legacy an @import in a loaded stylesheet is queued when it is written as url(), whatever follows it,
207+
* and not when it is a string or in a comment
208+
*/
209+
public function testProcessExternalCssImportsQueuesEachUrlInLegacyMode()
210+
{
211+
$this->mpdf->cssMode = CssMode::LEGACY;
212+
$externalCss = [];
213+
$count = 0;
214+
215+
$this->cssLoader->processExternalCssImports(
216+
'/* @import url(old.css); */ @import "base.css"; @import url(screen.css) screen; @import url(print.css) print; p { color: red; }',
217+
'http://example.com/css/main.css',
218+
$externalCss,
219+
$count
220+
);
221+
222+
$this->assertSame(['http://example.com/css/screen.css', 'http://example.com/css/print.css'], $externalCss);
223+
$this->assertSame(2, $count);
224+
}
225+
173226
public function testResolveBackgroundUrls()
174227
{
175228
$css = 'body { background: url(images/bg.jpg); }';

0 commit comments

Comments
 (0)