Skip to content

Commit 923a3a0

Browse files
jakejackson1claude
andcommitted
Track the stack of open elements while HTML is written
WriteHTML() keeps a frame for each element open in the HTML it reads: its tag, id, classes, language and attributes, its position among its siblings and among those of its tag, and a record of the siblings closed before it. Selectors that look at ancestors and siblings will read it through Mpdf::getOpenElements(). It follows real tokens only, so forced page breaks leave it alone. It is put back with the rest of the state when a page-break-inside: avoid block unwinds. Headers, footers and the index set the flow's stack aside, and a positioned block's content is written against the stack as it stood inside the block. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 07af517 commit 923a3a0

6 files changed

Lines changed: 751 additions & 11 deletions

File tree

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,7 @@ These changes do not change output.
356356
* The coding standard and PHPStan run as one Lint workflow. The e-invoice and PDF/X-4 checks run on a pull request only when it changes the code they cover.
357357
* **PHPStan.** Fixes for newer PHP versions and PHPStan 2.2.15. [#6] [#295] [#319] [#451]
358358
* **Branch alias.** The Composer branch alias maps `dev-gravitypdf` to `8.x-dev`. [#3]
359+
* **Open elements.** `WriteHTML()` keeps a stack of the elements open in the HTML it reads, so that CSS rules can be matched against an element's parents, ancestors and earlier siblings rather than only the blocks mPDF lays out. Each element carries its position among its siblings and a record of the siblings before it. `Mpdf::getOpenElements()` reads it. [#533]
359360

360361
[mpdf/mpdf#83]: https://github.com/mpdf/mpdf/issues/83
361362
[mpdf/mpdf#747]: https://github.com/mpdf/mpdf/issues/747
@@ -750,6 +751,7 @@ These changes do not change output.
750751
[#526]: https://github.com/GravityPDF/mpdf/issues/526
751752
[#527]: https://github.com/GravityPDF/mpdf/issues/527
752753
[#528]: https://github.com/GravityPDF/mpdf/issues/528
754+
[#533]: https://github.com/GravityPDF/mpdf/issues/533
753755
[#549]: https://github.com/GravityPDF/mpdf/pull/549
754756
[#552]: https://github.com/GravityPDF/mpdf/issues/552
755757
[#560]: https://github.com/GravityPDF/mpdf/pull/560

‎src/Mpdf.php‎

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ class Mpdf implements \Psr\Log\LoggerAwareInterface
5050
use Strict;
5151
use FpdiTrait;
5252
use PageAreas;
53+
use TracksOpenElements;
5354
use MpdfPsrLogAwareTrait;
5455

5556
const VERSION = '8.3.2';
@@ -1250,6 +1251,7 @@ public function __construct(array $config = [], $container = null)
12501251
$this->defaultTableAlign = 'L';
12511252

12521253
$this->fixedPosBlockSave = [];
1254+
$this->openElements = $this->newOpenElementStack();
12531255
$this->extraFontSubsets = 0;
12541256

12551257
$this->blockContext = 1;
@@ -14663,6 +14665,20 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1466314665
if ($this->mb_enc) {
1466414666
mb_internal_encoding($this->mb_enc);
1466514667
}
14668+
// Headers, footers and positioned blocks are written in the middle of the flow as documents of their own, so the
14669+
// flow's open elements are set aside for them. A positioned block's content starts inside the block, whose frame
14670+
// the <div> standing in for it takes
14671+
$flowElements = null;
14672+
$standIn = false;
14673+
if ($mode === HTMLParserMode::HTML_HEADER_BUFFER) {
14674+
$flowElements = $this->openElements;
14675+
$standIn = $this->fixedPosBlockElements !== null;
14676+
$this->openElements = $standIn ? $this->fixedPosBlockElements : $this->newOpenElementStack();
14677+
} elseif ($init) {
14678+
$this->openElements = $this->newOpenElementStack();
14679+
}
14680+
$floor = $standIn ? count($this->openElements) : 1; // the frames this HTML cannot close
14681+
1466614682
$pbc = 0;
1466714683
$this->subPos = -1;
1466814684
$cnt = count($a);
@@ -14900,16 +14916,21 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1490014916
$this->fixedPosBlockDepth--;
1490114917
}
1490214918
if ($this->fixedPosBlockDepth == 0) {
14903-
$this->fixedPosBlockSave[] = [$this->fixedPosBlock, $this->fixedPosBlockBBox, $this->page];
14919+
// Its content was only buffered, so the open elements are as they were inside its start tag
14920+
$this->fixedPosBlockSave[] = [$this->fixedPosBlock, $this->fixedPosBlockBBox, $this->page, $this->openElements];
1490414921
$this->fixedPosBlock = '';
1490514922
$this->inFixedPosBlock = false;
14923+
$this->closeNearestElement([$this->fixedPosBlockBBox[0]], [], $floor);
1490614924
continue;
1490714925
}
1490814926
$this->fixedPosBlock .= '<' . $e . '>';
1490914927
continue;
1491014928
}
1491114929
/* -- END CSS-POSITION -- */
1491214930

14931+
// Before CloseTag(), which puts back a page-break-inside: avoid block that ran onto another page
14932+
$this->closeElementsEndedBy($endtag, $floor);
14933+
1491314934
// mPDF 6
1491414935
// Correct for tags where HTML5 specifies optional end tags (see also OpenTag() )
1491514936
if ($this->allow_html_optional_endtags && !$parseonly) {
@@ -14995,6 +15016,9 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1499515016
$this->blk[$this->blklvl]['hide'] = true;
1499615017
$this->blk[$this->blklvl]['tag'] = $te; // mPDF 6
1499715018
}
15019+
$te = rtrim($te, '/');
15020+
$this->closeElementsImpliedBy($te, $floor);
15021+
$this->startElement($te, [], substr($e, -1) === '/');
1499815022
continue;
1499915023
}
1500015024

@@ -15076,22 +15100,36 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1507615100

1507715101
$attr[$name] = trim($value);
1507815102
}
15103+
$selfClosing = substr($e, -1) === '/';
15104+
$this->closeElementsImpliedBy($tag, $floor);
15105+
$token = $i;
1507915106
$this->tag->OpenTag($tag, $attr, $a, $i); // mPDF 6
15107+
// Unless it put back a page-break-inside: avoid block, which rewinds the parser to that block's start
15108+
// tag and the open elements to how they were there
15109+
if ($i === $token) {
15110+
if ($standIn) {
15111+
$standIn = false;
15112+
} else {
15113+
$this->startElement($tag, $attr, $selfClosing);
15114+
}
15115+
}
1508015116
/* -- CSS-POSITION -- */
1508115117
if ($this->inFixedPosBlock) {
1508215118
$this->fixedPosBlockBBox = [$tag, $attr, $this->x, $this->y];
1508315119
$this->fixedPosBlock = '';
1508415120
$this->fixedPosBlockDepth = 1;
1508515121
}
1508615122
/* -- END CSS-POSITION -- */
15087-
if (preg_match('/\/$/', $e)) {
15123+
if ($selfClosing) {
1508815124
$this->tag->CloseTag($tag, $a, $i);
1508915125
}
1509015126
}
1509115127
} // end TAG
1509215128
} // end of foreach($a as $i=>$e)
1509315129

1509415130
if ($close) {
15131+
$this->closeElementsDownTo($floor);
15132+
1509515133
// Close any open block tags
1509615134
for ($b = $this->blklvl; $b > 0; $b--) {
1509715135
$this->tag->CloseTag($this->blk[$b]['tag'], $a, $i);
@@ -15160,13 +15198,19 @@ function WriteHTML($html, $mode = HTMLParserMode::DEFAULT_MODE, $init = true, $c
1516015198
foreach ($this->fixedPosBlockSave as $fpbs) {
1516115199
$old_page = $this->page;
1516215200
$this->page = $fpbs[2];
15201+
$this->fixedPosBlockElements = $fpbs[3];
1516315202
$this->WriteFixedPosHTML($fpbs[0], 0, 0, 100, 100, 'auto', $fpbs[1]); // 0,0,10,10 are overwritten by bbox
15203+
$this->fixedPosBlockElements = null;
1516415204
$this->page = $old_page;
1516515205
}
1516615206
$this->fixedPosBlockSave = [];
1516715207
}
1516815208
/* -- END CSS-POSITION -- */
1516915209
}
15210+
15211+
if ($flowElements !== null) {
15212+
$this->openElements = $flowElements;
15213+
}
1517015214
}
1517115215

1517215216
/* -- CSS-POSITION -- */
@@ -25137,8 +25181,10 @@ function InsertIndex($usedivletters = 1, $useLinking = false, $indexCollationLoc
2513725181
}
2513825182

2513925183
$save_fpb = $this->fixedPosBlockSave;
25184+
$save_elements = $this->openElements;
2514025185
$this->WriteHTML($html);
2514125186
$this->fixedPosBlockSave = $save_fpb;
25187+
$this->openElements = $save_elements;
2514225188

2514325189
$this->breakpoints[$this->CurrCol][] = $this->y; // *COLUMNS*
2514425190
}
@@ -28247,7 +28293,7 @@ function AdjustHTML($html, $tabSpaces = 8)
2824728293
// Make self closing tabs valid XHTML
2824828294
// Tags which are self-closing: 1) Replaceable and 2) Non-replaced items
2824928295
$selftabs = 'input|hr|img|br|barcode|dottab';
28250-
$selftabs2 = 'indexentry|indexinsert|bookmark|watermarktext|watermarkimage|column_break|columnbreak|newcolumn|newpage|page_break|pagebreak|formfeed|columns|toc|tocpagebreak|setpageheader|setpagefooter|sethtmlpageheader|sethtmlpagefooter|annotation';
28296+
$selftabs2 = 'indexentry|indexinsert|bookmark|watermarktext|watermarkimage|column_break|columnbreak|newcolumn|newpage|page_break|pagebreak|formfeed|columns|toc|tocpagebreak|setpageheader|setpagefooter|sethtmlpageheader|sethtmlpagefooter|annotation|pageheader|pagefooter|textcircle';
2825128297

2825228298
// Fix self-closing tags which don't close themselves
2825328299
$html = preg_replace('/(<(' . $selftabs . '|' . $selftabs2 . ')[^>\/]*)>/i', '\\1 />', $html);

‎src/Tag.php‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@ class Tag
1212

1313
use Strict;
1414

15+
/**
16+
* @var array<string, true> The start tags that close an open <p>
17+
*/
18+
private static $paragraphClosers = [
19+
'ADDRESS' => true, 'ARTICLE' => true, 'ASIDE' => true, 'BLOCKQUOTE' => true, 'CENTER' => true, 'DIV' => true,
20+
'DL' => true, 'FIELDSET' => true, 'FORM' => true, 'H1' => true, 'H2' => true, 'H3' => true, 'H4' => true,
21+
'H5' => true, 'H6' => true, 'HGROUP' => true, 'HR' => true, 'MAIN' => true, 'NAV' => true, 'OL' => true,
22+
'P' => true, 'PRE' => true, 'SECTION' => true, 'TABLE' => true, 'UL' => true,
23+
];
24+
1525
/**
1626
* @var \Mpdf\Mpdf
1727
*/
@@ -170,6 +180,18 @@ public static function getTagClassName($tag)
170180
return $className;
171181
}
172182

183+
/**
184+
* Whether the start tag of an element closes an open <p>, as HTML lets its end tag be left out before it
185+
*
186+
* @param string $tag The tag name, uppercased
187+
*
188+
* @return bool
189+
*/
190+
public static function closesParagraph($tag)
191+
{
192+
return isset(self::$paragraphClosers[$tag]);
193+
}
194+
173195
public function OpenTag($tag, $attr, &$ahtml, &$ihtml)
174196
{
175197
// Correct for tags where HTML5 specifies optional end tags excluding table elements (cf WriteHTML() )
@@ -191,14 +213,8 @@ public function OpenTag($tag, $attr, &$ahtml, &$ihtml)
191213
$this->CloseTag('DD', $ahtml, $ihtml);
192214
$closed = true;
193215
}
194-
// p end tag may be omitted if immediately followed by an address, article, aside, blockquote, div, dl,
195-
// fieldset, form, h1, h2, h3, h4, h5, h6, hgroup, hr, main, nav, ol, p, pre, section, table, ul
196-
if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'P'
197-
&& ($tag == 'P' || $tag == 'DIV' || $tag == 'H1' || $tag == 'H2' || $tag == 'H3'
198-
|| $tag == 'H4' || $tag == 'H5' || $tag == 'H6' || $tag == 'UL' || $tag == 'OL'
199-
|| $tag == 'TABLE' || $tag == 'PRE' || $tag == 'FORM' || $tag == 'ADDRESS' || $tag == 'BLOCKQUOTE'
200-
|| $tag == 'CENTER' || $tag == 'DL' || $tag == 'HR' || $tag == 'ARTICLE' || $tag == 'ASIDE'
201-
|| $tag == 'FIELDSET' || $tag == 'HGROUP' || $tag == 'MAIN' || $tag == 'NAV' || $tag == 'SECTION')) {
216+
// p end tag may be omitted if immediately followed by one of the elements closesParagraph() lists
217+
if (!$closed && $this->mpdf->blk[$this->mpdf->blklvl]['tag'] == 'P' && self::closesParagraph($tag)) {
202218
$this->CloseTag('P', $ahtml, $ihtml);
203219
$closed = true;
204220
}

0 commit comments

Comments
 (0)