Repository navigation
Track the stack of open elements while HTML is written - #613
Merged
Merged
Conversation
jakejackson1
force-pushed
the
feature/533-open-element-stack
branch
2 times, most recently
from
September 30, 2026 01:54
679760c to
4a23472
Compare
jakejackson1
force-pushed
the
feature/533-open-element-stack
branch
2 times, most recently
from
September 30, 2026 02:17
923a3a0 to
06e875f
Compare
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>
jakejackson1
force-pushed
the
feature/533-open-element-stack
branch
from
September 30, 2026 02:35
06e875f to
e1ed3d5
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
To apply a CSS rule to the elements its selector matches, mPDF needs to know each element's ancestors and earlier siblings. Selectors such as
>,+,~,:first-childon any element, and descendant rules through inline ancestors need them. mPDF keeps neither: only block elements and table parts push a level (blk[],CssManager::$tablecascadeCSS), and nothing records siblings, so those rules are dropped or never match. This is step 13 of the plan in #520. It adds the state that #538, #537, #546 and #547 will read.Change
WriteHTML()keeps a stack of open elements, andMpdf::getOpenElements()returns it. The stack and the methods that keep it live in a new trait,Mpdf\TracksOpenElements(src/TracksOpenElements.php), which keeps the tree of elements so that each CSS rule can be matched against an element's parents, ancestors and earlier siblings.Mpdfuses it. Its methods arestartElement(),closeElementsEndedBy(),closeElementsImpliedBy(),closeNearestElement(),closeElementsDownTo(),recordClosedElement(),newOpenElementStack()andnewElementFrame(). The calls stay inWriteHTML(), the constructor andInsertIndex(). A trait's properties areMpdf's own, soStateSnapshotstill captures and restores$openElementswith the rest of the renderer state.langor inherited from an open ancestor;nthChildandnthOfType, counted from 1;children, a short record of each child closed so far. For the open child, these are the siblings before it, for+and~;childTypes, a count of those children by tag;computed, leftnullfor Inherit from the parent element's computed values under the opt-in cascade #547.Tag::OpenTag()/CloseTag(). So a forced page break, which closes and reopens blocks through those, leaves it alone. It is independent ofblk[].p,li,dt,dd,option,td,th,tr, and the table sections. These are the rulesTag::OpenTag()follows, and they are off whenallow_html_optional_endtagsis. The list of tags that close a<p>moved toTag::closesParagraph(), so both use it.br,hr,imgandinput, and mPDF's own tags written without content, such aspagebreak,indexentry,barcode,annotationandpageheader. The trait keeps its own list of them.AdjustHTML()only closes their start tag when no attribute value holds a/, so relying on its slash would leave<img src="images/a.png">open with the next element inside it. An element whose start tag closes itself is taken in the same way, and an end tag for a void element closes nothing.display: noneis tracked with its attributes, so the selectors that look at its siblings can read them.<table>gets atbodyframe, as in a browser's tree, sotable > tbody > trwill match as it does there.tta/tts/ttz, which mPDF inserts around substituted characters, are not tracked.page-break-inside: avoid. The frame is pushed afterOpenTag()returns and popped beforeCloseTag()is called, so the snapshot thatBlockTagrestores never holds it. IfOpenTag()itself unwinds a kept block, through an implied end tag, the parser rewinds and nothing is pushed.HTML_HEADER_BUFFERwrite sets the flow's stack aside and starts from an empty document, then puts the flow's stack back. That covers headers measured in the middle of the flow and those written at the end.InsertIndex()does the same around the index it writes.WriteFixedPosHTML(). The<div>that stands in for the block takes the block's own frame, and the content cannot close the frames it was given.WriteFixedPosHTML()'s$boundingargument is unchanged.WriteHTML()in parts keeps the stack across calls until a call starts a new document ($init), asblk[]does. Closing the document pops every frame into the document's record.The PR changes nothing on the page. The snapshot suite passes with no fixture updated, so there is no new snapshot test.
Performance
The stack costs under 1 µs per element, for its start and end tag together. I measured it two ways on three documents:
Direct cost. In a copy of the branch,
hrtime()around every stack call, rendering one document at a time:End to end.
new Mpdf,WriteHTML()andOutput(), one PHP process per run. Base (origin/gravitypdf) and branch runs alternate. Each figure is the mean of 10 runs, with the standard deviation in brackets. Cold runs start with an emptytempDir, hot runs reuse it. PHP 8.5.4:Most of these differences are within one standard deviation. Other jobs were running on the machine, and one earlier run was noisy enough that I discarded it.
Tests
OpenElementStackTestrecords the open elements as each piece of text is read, throughOpenElementsRecordingMpdf, a subclass ofUnwindCountingMpdfthat overrides_saveTextBuffer()and_saveCellTextBuffer(). It checks the path and positions for:tbodyimplied for bare rows;allow_html_optional_endtagsis off;</div>inside a cell for adivoutside the table;img,annotationandpageheaderwith a/in an attribute value;lang;WriteHTML()in parts;With the source change reverted, every test fails. I also removed each hard-part guard in turn (header set-aside, unwind check, floor, stand-in, init reset, cell scope, implied end tags, implied tbody, index restore, closing pop, positioned pop). A test fails for each.
Checks
composer test: OK. 5098 tests, 31 skipped for missing optional packages or ungenerated data. The snapshot suite ran with Imagick and Ghostscript, and no fixture changed.composer cs: clean.Part of #520. Closes #533.
🤖 Generated with Claude Code