Skip to content

Track the stack of open elements while HTML is written - #613

Merged
jakejackson1 merged 1 commit into
gravitypdffrom
feature/533-open-element-stack
Sep 30, 2026
Merged

jakejackson1 merged 1 commit into
gravitypdffrom
feature/533-open-element-stack

Conversation

@jakejackson1

@jakejackson1 jakejackson1 commented Sep 29, 2026 •

Copy link
Copy Markdown
Member

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-child on 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, and Mpdf::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. Mpdf uses it. Its methods are startElement(), closeElementsEndedBy(), closeElementsImpliedBy(), closeNearestElement(), closeElementsDownTo(), recordClosedElement(), newOpenElementStack() and newElementFrame(). The calls stay in WriteHTML(), the constructor and InsertIndex(). A trait's properties are Mpdf's own, so StateSnapshot still captures and restores $openElements with the rest of the renderer state.

  • Frames. The first frame stands for the document, or for the header, footer or positioned block being written. Each element's frame holds:
    • its tag, id, classes and attributes;
    • its language, from its own lang or inherited from an open ancestor;
    • nthChild and nthOfType, 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, left null for Inherit from the parent element's computed values under the opt-in cascade #547.
  • Where it is kept. The stack follows real tokens in the token loop, not Tag::OpenTag()/CloseTag(). So a forced page break, which closes and reopens blocks through those, leaves it alone. It is independent of blk[].
    • An end tag closes the nearest open element with its name, and everything open inside it. It is ignored if there is none, or if the element is outside the table cell or caption the tag is written in.
    • A start tag closes the elements whose end tag HTML lets be left out: p, li, dt, dd, option, td, th, tr, and the table sections. These are the rules Tag::OpenTag() follows, and they are off when allow_html_optional_endtags is. The list of tags that close a <p> moved to Tag::closesParagraph(), so both use it.
    • A void element is counted among its siblings but never pushed. These are HTML's void elements, such as br, hr, img and input, and mPDF's own tags written without content, such as pagebreak, indexentry, barcode, annotation and pageheader. 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.
    • An element inside one hidden with display: none is tracked with its attributes, so the selectors that look at its siblings can read them.
    • A row written straight into a <table> gets a tbody frame, as in a browser's tree, so table > tbody > tr will match as it does there.
    • tta/tts/ttz, which mPDF inserts around substituted characters, are not tracked.
  • Hard parts:
    • page-break-inside: avoid. The frame is pushed after OpenTag() returns and popped before CloseTag() is called, so the snapshot that BlockTag restores never holds it. If OpenTag() itself unwinds a kept block, through an implied end tag, the parser rewinds and nothing is pushed.
    • Headers and footers. A HTML_HEADER_BUFFER write 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.
    • Positioned blocks (Match descendant selectors inside an absolutely positioned block #474). The stack as it stands inside the block is saved with the buffered block, and the replay sets it for 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 $bounding argument is unchanged.
    • WriteHTML() in parts keeps the stack across calls until a call starts a new document ($init), as blk[] 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:

  • a 400-row table, 5 cells a row (2,802 elements);
  • 100 sections of paragraphs, inline markup and lists (5,400 elements);
  • 60 paragraphs of nested inline markup (9,660 elements).

Direct cost. In a copy of the branch, hrtime() around every stack call, rendering one document at a time:

Document Stack time Render time Share
Table 4.2–4.7 ms ~330 ms ~1.4%
Paragraphs 7.3–7.7 ms ~530 ms ~1.4%
Nested inline 7.4–8.1 ms ~220 ms ~3.4%

End to end. new Mpdf, WriteHTML() and Output(), 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 empty tempDir, hot runs reuse it. PHP 8.5.4:

Document Cold: base Cold: branch Hot: base Hot: branch
Table 326.3 ms (9.8) 335.8 ms (18.1), +2.9% 324.0 ms (9.9) 328.3 ms (5.1), +1.3%
Paragraphs 528.7 ms (14.3) 537.3 ms (21.4), +1.6% 524.7 ms (16.6) 536.4 ms (20.5), +2.2%
Nested inline 213.2 ms (2.9) 223.7 ms (8.9), +4.9% 214.5 ms (6.4) 218.5 ms (2.4), +1.8%

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

OpenElementStackTest records the open elements as each piece of text is read, through OpenElementsRecordingMpdf, a subclass of UnwindCountingMpdf that overrides _saveTextBuffer() and _saveCellTextBuffer(). It checks the path and positions for:

  • omitted end tags, in lists, definition lists, paragraphs, selects and tables, including a tbody implied for bare rows;
  • no implied end tags when allow_html_optional_endtags is off;
  • stray end tags, including a </div> inside a cell for a div outside the table;
  • empty elements counted as siblings, including mPDF's own tags written without a slash, and an img, annotation and pageheader with a / in an attribute value;
  • a frame's id, classes, attributes and inherited lang;
  • nested tables;
  • a forced page break inside nested blocks;
  • a kept block that unwinds, and a kept paragraph unwound by the next start tag;
  • a header measured in the middle of the flow and then written on its page;
  • a positioned block inside an inline element, with a stray end tag in its content;
  • WriteHTML() in parts;
  • an index inserted in the flow;
  • an element inside a hidden one keeping its attributes;
  • closing the document.

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.
  • PHPStan 2.2: no errors.

Part of #520. Closes #533.

🤖 Generated with Claude Code

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
jakejackson1 force-pushed the feature/533-open-element-stack branch from 06e875f to e1ed3d5 Compare September 30, 2026 02:35
@jakejackson1
jakejackson1 merged commit 258839c into gravitypdf Sep 30, 2026
10 checks passed
@jakejackson1
jakejackson1 deleted the feature/533-open-element-stack branch September 30, 2026 02:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

create-upstream-pr enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Track the stack of open elements while parsing HTML

1 participant