Goal: attach styles and geometry to the same DOM
The DOM produced from HTML must flow into style calculation and layout unchanged in identity. Rebuilding a more convenient tree for CSS would make it difficult to connect parsed nodes with rendered results. The project’s render function connects parse_html, parse_css, compute_styles, and layout_node, returning the document, a style array, layout boxes, and drawing commands. Each node identifier in those outputs refers to a node in the same document.
This is a teaching renderer with vertical block flow. It does not reproduce real font shaping, inline formatting, Flexbox, Grid, or margin collapsing. Its smaller contract makes useful questions inspectable in Rust: which intermediate values change when only a color changes, when a width changes, or when an element becomes hidden? After the earlier conceptual CSS demo, the goal is to verify these intermediate values rather than relying only on the final picture.
Fix the supported CSS language first
parse_css supports only the universal selector, a tag name, a class selector, and an ID selector. Their specificity values are 0, 1, 10, and 100; equal-specificity rules retain source order, so later declarations apply later. Descendant selectors and !important do not become supported merely because a host browser understands them. Inspect diagnostics for unsupported rules and values. A class selector matches a whitespace-separated name in the existing node’s class attribute without duplicating that node.
The property set is limited to width, height, margin, padding, color, background or background-color, and display. Dimensions are bounded from zero through 640, with auto additionally available for width and height. Colors accept short or long hexadecimal forms and a limited set of names. Test negative lengths, unsupported units, and compound selectors to locate the language boundary. Restricting the accepted set makes the implementation teachable; it must not be presented as support for the full CSS language.
Computed values: inheritance and overwrite order
compute_styles walks nodes in document order. Because a parent already exists before its children, the function can begin each child’s style with the parent’s color and then apply matching element rules in specificity order. Copying width or padding indiscriminately from a parent would accidentally reproduce its dimensions on the child. The teaching implementation inherits color; inheritance is a property-specific rule rather than a wholesale copy of the parent style object.
With p{color:blue} and #lead{color:red}, a paragraph whose ID is lead ends up red even when the ID rule appeared first. With two rules having the same p selector, the later declaration wins. Applying rules solely in discovery order misses specificity, while an unstable specificity sort can lose equal-priority source order. Test these as separate dimensions. Inspect the style array for an element and its text child so you can explain both the winning declaration and the subsequent inheritance path.
Worked trace: width 120, margin 4, padding 8
Use <div id="card"><p>AB</p><p>CD</p></div> and #card{width:120px;padding:8px;margin:4px}. The root has 320 pixels available. The card’s content width is 120, its painted box width is 120 + 2 × 8 = 136, and its top-left corner is (4,4). Its content begins at (12,12). Each paragraph contains one 20-pixel text line, placing the paragraphs at y values 12 and 32.
The card’s content height is 40. Adding top and bottom padding produces a box height of 56, and adding both margins gives an occupied height of 64 returned to the parent. Change width to 40 and reason about wrapping without changing DOM links or node identifiers. In a color-only comparison, expect the geometry to remain equal while drawing-command colors differ. Predicting these values before looking at the picture helps identify whether a discrepancy originated in rule application or in geometric placement.
| Value | Calculation | Result |
|---|---|---|
| Content width | width | 120 |
| Box width | 120 + 2 × 8 | 136 |
| Content origin | (4 + 8, 4 + 8) | (12,12) |
| Occupied height | 40 + 2 × 8 + 2 × 4 | 64 |
Handle text and hidden content in the traversal
layout_node advances each sibling using the occupied height returned by the previous child. Text collapses whitespace, counts Unicode characters, and uses the teaching metrics of eight pixels per character and twenty pixels per line. Those are fixed model values, not measurements of actual fonts. Japanese glyphs and emoji therefore need not match a host browser’s rendered width. The fixed metrics make wrapping and line height reproducible; inspect narrow widths as well as the normal case.
For display:none, traversal skips layout of the node and its descendants and contributes zero occupied height. The nodes remain in the DOM, allowing a later style calculation to reveal them without reparsing a different tree. An explicit height chooses content height, but this project does not implement clipping. If child drawing commands extend beyond that height, distinguish the parent’s box dimensions from the child’s paint extent rather than assuming that fixed height automatically hides overflow.
Separate arithmetic checks from implementation tests
The following standalone Rust program checks the arithmetic used in the worked trace. It keeps painted width, content origin, and occupied height as distinct quantities. The project tests must additionally pass the actual HTML and CSS to render and inspect the corresponding node’s box. An arithmetic check can pass while the implementation reads another node’s style, so these are complementary forms of evidence rather than interchangeable tests.
Include width zero, display:none, equal-specificity conflicts, inherited color, unsupported display:flex, and an out-of-range length. When an invalid declaration produces a diagnostic, inspect whether valid declarations in the same input still apply according to the parser’s contract. Mixing valid and invalid declarations reveals the intended scope of partial acceptance. Before changing an expected result to make a test pass, explain whether you are revising the teaching specification or correcting code that violated it.
// Standalone box arithmetic; related to layout_node content-box dimensions.
fn main() {
let (width, padding, margin, content_height) = (120, 8, 4, 40);
assert_eq!(width + 2 * padding, 136);
assert_eq!(margin + padding, 12);
assert_eq!(content_height + 2 * padding + 2 * margin, 64);
}Exercise: connect one edit to intermediate values
In the exercise version, implement computed-style conflict resolution before completing placement based on child heights. Changing both stages at once makes a color error difficult to distinguish from a coordinate error. Edit color, padding, and display one at a time and record which of the DOM, styles, boxes, and commands changed. Search for a case where the visible result looks similar despite an incorrect intermediate value; that is a useful warning against screenshot-only validation.
When comparing with the completed version, ensure each output belongs to the current input rather than a previous run or a different stylesheet. Treat the commands returned by Rust as the renderer’s result, instead of applying the user’s CSS to the host UI and presenting that as execution. Finally, choose an unsupported feature and design the extra data and invariants it would require. Record local extensions as self-reported work, separately from the web questions that the site actually grades.