Skip to content

Commit dce3ce4

Browse files
jakejackson1claude
andcommitted
Match :last-child, :only-child, :empty and the other pseudo-classes that look at what follows an element
WriteHTML() walks its tokens once before writing them, through the methods that keep the stack of open elements, and records how many children each element has, of each tag, and whether it is empty. Each frame takes that record when it is made, and the matcher counts from the parent's totals. An element a call leaves open is not known in full, so these pseudo-classes, and :not() of them, do not match its children in that call. The spans mPDF adds for a substitute font are marked as script-run spans are, so they are not counted among their siblings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f1b1c53 commit dce3ce4

19 files changed

Lines changed: 1540 additions & 45 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ New features
111111
* **Descendant rules through inline elements.** A descendant rule whose ancestor is an inline element, a block inside a table cell, or the `tbody` a table leaves out, such as `span em`, or `.note b` for a `<span class="note">`, applies. [mpdf/mpdf#830] [#538] [#621]
112112
* **Attribute selectors and `:lang()`.** `[a]`, `[a=v]`, `[a~=v]`, `[a|=v]`, `[a^=v]`, `[a$=v]` and `[a*=v]`, with the `i` and `s` flags, match as in HTML: case-insensitively for the attributes HTML lists as such, and case-sensitively for the rest. `:lang()` matches the language an element inherits, from an ancestor or from the `<html>` or `<body>` tag. [mpdf/mpdf#134] [mpdf/mpdf#1838] [#538] [#627]
113113
* **`:not()`, `:is()` and `:where()`.** Each takes a selector list whose selectors may have combinators, such as `p:not(.note, div > p)` or `:is(h2, h3) + p`. `:is()` and `:where()` leave out a selector they cannot read, as browsers do. `:not()` and `:is()` weigh as their most specific argument, and `:where()` as nothing. Rules using them were dropped before. [#538] [#628]
114+
* **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]
115+
* `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.
116+
* `: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.
114117

115118
Performance
116119
-----------
@@ -193,6 +196,7 @@ Bugfixes
193196
* `background-size` lengths such as `60mm` or `100px` drew the image 2.83 times too small, because they were used as points. [#574]
194197
* A stylesheet `url()` did not load its image when the path had spaces or parentheses, when there was whitespace inside the parentheses, or when it was an SVG data URI that is not base64, such as Bootstrap's `form-select` arrow. [#573]
195198
* `linear-gradient(to bottom, …)` and `to top` were drawn upside down, and so was the vertical half of `to bottom right` and the other corners. Angles ran counter-clockwise from pointing right, so `90deg` drew bottom to top. A gradient now runs as CSS Images gives: `0deg` points up and angles turn clockwise, `turn` is read, and a corner keyword leaves the other two corners halfway along. `-moz-`, `-webkit-` and `-o-` gradients keep their legacy angles, and their side keyword, such as `left`, names the side the gradient starts from. [#577]
199+
* Characters mPDF moved into a substitute font (`useSubstitutions`, and the fonts for supplementary planes) were wrapped in a `<span>` that stylesheet rules reached, so `span { border: 1px solid }` drew a box around them, and the span counted among its siblings for `:nth-child()`. In the standard CSS mode no rule reaches that span and it is not counted, as a browser has no such element. The legacy mode styles it as before. [#634]
196200

197201
### Images and SVG
198202

@@ -785,6 +789,7 @@ These changes do not change output.
785789
[#528]: https://github.com/GravityPDF/mpdf/issues/528
786790
[#533]: https://github.com/GravityPDF/mpdf/issues/533
787791
[#535]: https://github.com/GravityPDF/mpdf/issues/535
792+
[#537]: https://github.com/GravityPDF/mpdf/issues/537
788793
[#538]: https://github.com/GravityPDF/mpdf/issues/538
789794
[#549]: https://github.com/GravityPDF/mpdf/pull/549
790795
[#552]: https://github.com/GravityPDF/mpdf/issues/552
@@ -831,3 +836,4 @@ These changes do not change output.
831836
[#631]: https://github.com/GravityPDF/mpdf/pull/631
832837
[#632]: https://github.com/GravityPDF/mpdf/issues/632
833838
[#633]: https://github.com/GravityPDF/mpdf/pull/633
839+
[#634]: https://github.com/GravityPDF/mpdf/pull/634

‎src/Css/SelectorCompiler.php‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@
2121
* names attributes, and the operator empty for [name]. Values are compared case-insensitively, and held lowercased,
2222
* for the attributes HTML lists as such, for id and class, whose values the tokenizer uppercases, and with the i flag.
2323
*
24-
* Pseudo-classes are held as [name, arguments...]: ['nth-child', a, b] and ['nth-of-type', a, b] for an+b, which
25-
* :first-child and :first-of-type are written as, ['lang', ranges] with each language range lowercased, and
26-
* ['not', selectors] and ['is', selectors] with each selector compiled. :where() is held as :is(), its specificity
27-
* being the only difference.
24+
* Pseudo-classes are held as [name, arguments...]: ['nth-child', a, b], ['nth-of-type', a, b], ['nth-last-child', a, b]
25+
* and ['nth-last-of-type', a, b] for an+b, which :first-child, :first-of-type, :last-child and :last-of-type are
26+
* written as, ['only-child'], ['only-of-type'] and ['empty'], ['lang', ranges] with each language range lowercased,
27+
* and ['not', selectors] and ['is', selectors] with each selector compiled. :where() is held as :is(), its
28+
* specificity being the only difference.
2829
*/
2930
class SelectorCompiler
3031
{
@@ -44,6 +45,20 @@ class SelectorCompiler
4445
'TARGET' => true, 'TEXT' => true, 'TYPE' => true, 'VALIGN' => true, 'VALUETYPE' => true, 'VLINK' => true,
4546
];
4647

48+
/**
49+
* @var array[] The pseudo-classes written without an argument, compiled. Those that count from the first or last
50+
* sibling are held as the nth formula they stand for
51+
*/
52+
private static $pseudoClassesWithoutArguments = [
53+
'first-child' => ['nth-child', 0, 1],
54+
'first-of-type' => ['nth-of-type', 0, 1],
55+
'last-child' => ['nth-last-child', 0, 1],
56+
'last-of-type' => ['nth-last-of-type', 0, 1],
57+
'only-child' => ['only-child'],
58+
'only-of-type' => ['only-of-type'],
59+
'empty' => ['empty'],
60+
];
61+
4762
/**
4863
* @var Mpdf
4964
*/
@@ -242,11 +257,8 @@ private function parsePseudoClass($text, &$pos, array &$specificity, &$universal
242257
$specificity[1]++;
243258
}
244259

245-
if ($name === 'first-child') {
246-
return ['nth-child', 0, 1];
247-
}
248-
if ($name === 'first-of-type') {
249-
return ['nth-of-type', 0, 1];
260+
if (isset(self::$pseudoClassesWithoutArguments[$name])) {
261+
return self::$pseudoClassesWithoutArguments[$name];
250262
}
251263

252264
if (!$this->isAt($text, $pos, '(')) {
@@ -269,7 +281,7 @@ private function parsePseudoClass($text, &$pos, array &$specificity, &$universal
269281
return $ranges === null ? null : ['lang', $ranges];
270282
}
271283

272-
if ($name !== 'nth-child' && $name !== 'nth-of-type') {
284+
if (!in_array($name, ['nth-child', 'nth-of-type', 'nth-last-child', 'nth-last-of-type'], true)) {
273285
return null;
274286
}
275287

‎src/Css/SelectorMatcher.php‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ class SelectorMatcher
2222
/** It fails for this element and for any other whose ancestors are all among this one's */
2323
const FAILS_FOR_ANCESTORS = 2;
2424

25+
/**
26+
* @var bool Whether a pseudo-class that needs what follows an element was matched against one for which that is
27+
* not known, and so did not match. :not() then does not match either
28+
*/
29+
private $undecided = false;
30+
2531
/**
2632
* Whether a selector matches the last element of a path
2733
*
@@ -158,12 +164,14 @@ private function matchesCompound(array $compound, array $path, $parent, $index)
158164

159165
/**
160166
* Whether a pseudo-class matches an element. :nth-child() counts the element among all its element siblings, and
161-
* :nth-of-type() among those with its tag; the document has no siblings, so it matches neither. :lang() matches the
162-
* language the element has or inherits. :is() matches when any selector in its list matches from the element,
163-
* combinators and all, and :not() when none does
167+
* :nth-of-type() among those with its tag. :nth-last-child(), :nth-last-of-type(), :only-child and :only-of-type
168+
* count from the parent's last child, and :empty reads whether the element holds anything, as
169+
* TracksOpenElements::readAhead() found; where it could not, they do not match. The document has no siblings, so
170+
* it matches none of these. :lang() matches the language the element has or inherits. :is() matches when any
171+
* selector in its list matches from the element, combinators and all, and :not() when none does and none was left
172+
* undecided
164173
*
165-
* @param array $pseudo A compiled pseudo-class: ['nth-child', a, b], ['nth-of-type', a, b], ['lang', ranges],
166-
* or ['is', selectors] or ['not', selectors]
174+
* @param array $pseudo A compiled pseudo-class, as SelectorCompiler describes them
167175
* @param array $element The element's frame or record, as element() gives it
168176
* @param array[] $path As matchesFrom() takes it
169177
* @param int $parent The depth of the element's parent on $path, as matchesFrom() takes it
@@ -174,13 +182,21 @@ private function matchesCompound(array $compound, array $path, $parent, $index)
174182
private function matchesPseudoClass(array $pseudo, array $element, array $path, $parent, $index)
175183
{
176184
if ($pseudo[0] === 'is' || $pseudo[0] === 'not') {
185+
$outer = $this->undecided;
186+
$this->undecided = false;
187+
$matched = false;
177188
foreach ($pseudo[1] as $selector) {
178189
if ($this->matchesFrom($selector, count($selector['compounds']) - 1, $path, $parent, $index) === self::MATCHES) {
179-
return $pseudo[0] === 'is';
190+
$matched = true;
191+
break;
180192
}
181193
}
182194

183-
return $pseudo[0] === 'not';
195+
// :not() of what could not be decided cannot be either
196+
$undecided = !$matched && $this->undecided;
197+
$this->undecided = $outer || $undecided;
198+
199+
return $pseudo[0] === 'is' ? $matched : !$matched && !$undecided;
184200
}
185201

186202
if ($pseudo[0] === 'lang') {
@@ -202,7 +218,31 @@ private function matchesPseudoClass(array $pseudo, array $element, array $path,
202218
return $this->isNth($pseudo[1], $pseudo[2], $index + 1);
203219
}
204220

205-
return $this->isNth($pseudo[1], $pseudo[2], $element['nthOfType']);
221+
if ($pseudo[0] === 'nth-of-type') {
222+
return $this->isNth($pseudo[1], $pseudo[2], $element['nthOfType']);
223+
}
224+
225+
// The rest need what follows the element, which is not always known
226+
$siblings = $path[$parent]['childTotal'];
227+
$ofType = isset($path[$parent]['childTypeTotals'][$element['tag']]) ? $path[$parent]['childTypeTotals'][$element['tag']] : null;
228+
if (($pseudo[0] === 'empty' ? $element['empty'] : $ofType) === null) {
229+
$this->undecided = true;
230+
231+
return false;
232+
}
233+
234+
switch ($pseudo[0]) {
235+
case 'nth-last-child':
236+
return $this->isNth($pseudo[1], $pseudo[2], $siblings - $index);
237+
case 'nth-last-of-type':
238+
return $this->isNth($pseudo[1], $pseudo[2], $ofType - $element['nthOfType'] + 1);
239+
case 'only-child':
240+
return $siblings === 1;
241+
case 'only-of-type':
242+
return $ofType === 1;
243+
default:
244+
return $element['empty'];
245+
}
206246
}
207247

208248
/**
@@ -296,7 +336,8 @@ private function isNth($a, $b, $position)
296336
* @param int $parent The depth of the element's parent on $path, as matchesFrom() takes it
297337
* @param int $index The element's index among its parent's children, as matchesFrom() takes it
298338
*
299-
* @return array Its tag, id, classes, attr and nthOfType, and for an open element or the document its lang
339+
* @return array Its tag, id, classes, attr and nthOfType, for an element its empty, and for an open element or
340+
* the document its lang
300341
*/
301342
private function element(array $path, $parent, $index)
302343
{

‎src/Mpdf.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ class Mpdf implements \Psr\Log\LoggerAwareInterface
6060
const OBJECT_IDENTIFIER = "\xbb\xa4\xac";
6161

6262
/**
63-
* The attribute, as the tokenizer names it, that marks a span markScriptToLang() wraps a run of another script in
63+
* The attribute, as the tokenizer names it, that marks a span markScriptToLang() wraps a run of another script in,
64+
* or one the character substitution wraps a run it moves into another font in
6465
*/
6566
const SCRIPT_RUN_ATTRIBUTE = 'DATA-MPDF-SCRIPT-RUN';
6667

@@ -14698,6 +14699,12 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1469814699
$this->openElements = $this->newOpenElementStack();
1469914700
}
1470014701
$floor = $standIn ? count($this->openElements) : 1; // the frames this HTML cannot close
14702+
// What is read ahead is for this call's tokens only. A header or index written in the middle of the flow puts
14703+
// the flow's back when it is done. The legacy mode reads nothing ahead, as it drops the selectors that need it
14704+
$outerLookAhead = $this->lookAhead;
14705+
if ($this->cssMode === CssMode::STANDARD) {
14706+
$this->readAhead($a, $floor, $standIn, $close);
14707+
}
1470114708

1470214709
$pbc = 0;
1470314710
$this->subPos = -1;
@@ -15239,6 +15246,7 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1523915246
if ($flowElements !== null) {
1524015247
$this->openElements = $flowElements;
1524115248
}
15249+
$this->lookAhead = $outerLookAhead;
1524215250
}
1524315251

1524415252
/* -- CSS-POSITION -- */
@@ -26740,7 +26748,7 @@ function SubstituteCharsSIP(&$writehtml_a, &$writehtml_i, &$writehtml_e)
2674026748
return 0;
2674126749
}
2674226750
$writehtml_a[$writehtml_i] = $writehtml_e = $m[1];
26743-
array_splice($writehtml_a, $writehtml_i + 1, 0, ['span style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]);
26751+
array_splice($writehtml_a, $writehtml_i + 1, 0, ['span data-mpdf-script-run style="font-family: ' . $font . '"', $m[2], '/span', $m[3]]);
2674426752
$this->subPos = $writehtml_i;
2674526753
return 4;
2674626754
}
@@ -27181,7 +27189,7 @@ private function substitutionStep($text, $from, $start, $l, $font, $replacement
2718127189
return [
2718227190
'before' => mb_substr($text, 0, $offset, 'UTF-8'),
2718327191
'insert' => $replacement === null
27184-
? ['span style="font-family: ' . $font . '"', mb_substr($text, $offset, $l, 'UTF-8'), '/span']
27192+
? ['span data-mpdf-script-run style="font-family: ' . $font . '"', mb_substr($text, $offset, $l, 'UTF-8'), '/span']
2718527193
: [$font, $replacement, '/' . $font],
2718627194
'rest' => mb_substr($text, $offset + $l, null, 'UTF-8'),
2718727195
'from' => $start + $l,

0 commit comments

Comments
 (0)