Layout Engine

Layout Engine

The layout layer turns a styled DOM into geometry: a box tree, then fragments with sizes and positions. It is the stage after computed styles, and its outputs are plain Python objects you can inspect.


From DOM to Box Tree

build_box_tree() produces a BoxRoot of BoxNode entries from a styled document, classifying each element’s display model via classify_display() against the Display enumeration. ComputedStyle and EdgeSizes carry the per-box style and box-model measurements.

Block Layout

layout_block_tree() performs block-level layout over the box tree, producing a FragmentRoot containing BlockFragment entries with resolved geometry.

Inline Layout

Inline content is shaped into ShapedRun and InlineTextFragment pieces, assembled into LineFragment lines via layout_inline_fragments() and flush_inline_run().

Pagination

paginate_fragments() splits fragment output into PageFragment pages, honouring BreakHints, with PageMarginBoxes modelling page-margin areas and flush_page() finalizing each page.


Tips and Best Practices

  • Resolve computed styles before layout — the box tree derives from styled elements
  • Inspect EdgeSizes when box dimensions look wrong; margins and padding resolve there
  • Keep the box tree and fragment tree distinct in your mental model: boxes describe structure, fragments describe placed geometry

Common Issues

IssueCauseFix
Empty fragment outputLayout run on an unstyled or empty treeAttach stylesheets and content first
Unexpected display classificationElement’s computed display differs from assumptionCheck classify_display() result for the box
Page breaks in odd placesBreak hints not setProvide BreakHints to paginate_fragments()

FAQ

What is the difference between a box and a fragment?

Boxes (BoxNode) describe the layout structure derived from styles; fragments (BlockFragment, LineFragment) are the placed results with geometry.

Does the engine handle pagination?

Yes — paginate_fragments() produces PageFragment pages with margin boxes.

Where do text runs come from?

Inline content is shaped into ShapedRun objects and assembled into LineFragment lines.


API Reference Summary

Class/MethodDescription
build_box_treeDerive the box tree from a styled DOM
layout_block_treeRun block layout over the box tree
layout_inline_fragmentsAssemble inline content into lines
paginate_fragmentsSplit fragments into pages
BoxNodeOne box in the layout structure
PageFragmentOne laid-out page

See Also