iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌕

Building My Own Browser Layout Engine from Scratch

に公開

I've wanted to build my own browser for a long time. So, I'm doing it.

This time, I built the browser's GUI layer, primarily the layout coordinate calculation module, from scratch. It might be easier to think of it as calculating coordinates for the CSS box model, Flex, and Grid.

I also implemented parts of the HTML parser, CSS parser, CSS query engine, and painting, but those were mainly for testing layout visualization. The part I really built properly is the coordinate calculation logic.

What I built

A rough playground

https://crater-playground.mizchi.workers.dev/

It looks like this:

This is Google rendered in a terminal using Sixel. Since this project focuses on coordinate calculation, background-color and fonts aren't fully implemented yet. However, debugging just with rectangles was tough, so I added a minimal bitmap font renderer.

Repository

https://github.com/mizchi/crater

npm: @mizchi/crater

https://www.npmjs.com/package/@mizchi/crater

WASM module on wa.dev

https://wa.dev/mizchi:crater

So, here is the story of the development process and some thoughts.

Existing implementations

A famous modular layout engine is the Yoga Layout Engine. It is used inside React Native and Ink TUI, primarily handling flexbox calculations.

https://www.yogalayout.dev/

There is also a Rust implementation called taffy. It is used in Firefox Servo, Zed Editor, etc., and implements not just flexbox but also Grid.

https://github.com/DioxusLabs/taffy

However, taffy by itself doesn't have the capability to calculate CSS. You need to parse CSS, calculate values including user environments, consider the effects of parent-child cascading, and finally resolve the fixed coordinates.

For CSS calculation, the CSS Style Engine layer, such as Stylo used in Firefox/Servo, is well-known.

https://github.com/servo/stylo

Blitz is an example that combines Taffy + Stylo.

https://blitz.is/

After trying various things, I concluded that if you just want to build a browser in Rust, it's best to refer to Blitz's implementation and use taffy and stylo directly.

Since this was for learning purposes and I wanted to write everything from scratch in Moonbit, I only used their implementations as a reference.

Setting Goals

  • To be used as a replacement for Yoga
    • Act as a foundation for building an Ink Alternative in TUI
  • To be written in pure Moonbit
    • Design it to be modular so it can be incorporated into other implementations in the future
    • Distribute via npm for JS builds and wa.dev for WebAssembly

Implementation Steps

Basically, the goal is to pass the Web Platform Tests (WPT). This is a collection of test cases used for standard browser compatibility testing in Chrome, Firefox, Webkit, and others.

https://web-platform-tests.org/

While I am writing the core parts myself, standardizing requires handling a huge number of cases. I had the AI work hard on this.

Even with AI, there is still much for a human to do. The user needs deep understanding to specify which test cases to prioritize, which benchmarks to target, and which algorithms to choose. I provided instructions while observing the implementation progress. While having ChatGPT research existing implementation methods and the latest techniques, I reviewed and corrected the code.

However, WPT contains many edge cases that nitpick small details. Instead of aiming to pass WPT from the start, I decided to first port the tests from Taffy.

Porting Taffy's Tests

I ported the text_fixtures and test cases from Taffy as they were.

https://github.com/DioxusLabs/taffy/tree/main/test_fixtures

It ended up looking like this:

Module Passed Total Rate
Block 204 224 91.1%
Flexbox 547 607 90.1%
Grid 266 331 80.3%

Grid has many complex specifications, so it is a bit tricky, but I feel like I can manage it with some effort.

Also, in the process of building this, I found a specification violation in Taffy itself and reported it, which led to a discussion about fixing it as a breaking change.

https://github.com/DioxusLabs/taffy/issues/908

I ended up indirectly contributing to Servo, so that was a good result.

Passing the WPT: Web Platform Tests

Once I had passed a certain amount of Taffy's tests, I started targeting layout-related tests from WPT for implementation.

  • css/contain
  • css/flexbox
  • css/grid
  • css/overflow
  • css/position

https://github.com/web-platform-tests/wpt

Currently, it looks like this:

Module Passed Total Rate
css-flexbox 148 234 63.2%
css-grid 17 30 56.7%
css-sizing 23 50 46.0%
css-overflow 8 20 40.0%
css-position 11 30 36.7%

You might wonder if this test passing rate is acceptable, but the parts I haven't done mainly involve things like vertical text in writing-mode or dependencies on baseline rendering results for proportional fonts. My current implementation strongly assumes monospaced fonts for coordinate calculations.

Since building this is just for fun, it would be overkill, so I am selecting and implementing tests based on the test cases. I have also skipped implementing things like display: table.

Lessons Learned / Challenges

Passing WPT is Tough!

Passing WPT is quite grueling. To be honest, there are many test cases where I question if it is truly necessary to account for such edge cases, but I suppose this is required to maintain browser compatibility. The WPT pass rate is a completely different story from the coverage of practical features; honestly, even passing a few items is enough to achieve the behavior people generally associate with a browser.

Covering WPT is, in a way, a testament to the obsession with Web standards.

Node Recalculation Should Be Considered from the Start

I implemented this with some performance tuning in mind, and what was particularly effective for performance was the "Double Dirty Bit" during partial recalculations of the render tree.

https://webkit.org/blog/116/webcore-rendering-iii-layout-basics/

When a change is made to the tree, this places a dirty flag on nodes that require layout recalculation, and only those parts are recalculated. It feels like extending the virtual DOM calculation not just to the nodes, but also to the coordinates.

By introducing the Double Dirty Bit and caching the computed results, partial recalculations became 7–20 times faster. Since every browser implements something similar, it seems wise to account for this implementation from the very beginning.

Extrinsic vs. Intrinsic Sizing and the Utility of CSS: Contain

One of the most difficult aspects of CSS layout calculation is that it involves two types of sizing: extrinsic size, which is calculated based on parent specifications, and intrinsic size, which is determined by the element's own child elements. Because of this, each node must perform three passes (parent/child/self) to finalize the coordinates.

While implementing this, I needed to re-examine various properties and remembered the contain element. This allows for the suppression of recalculations altogether by explicitly specifying the intrinsic size.

https://developer.mozilla.org/en-US/docs/Web/CSS/contain

I wondered if this was what I needed for coordinate optimization, but I only found vague claims that "it makes things faster."

So, I implemented it myself and used it to prune calculations. At that point, I checked if the existing benchmarks I had prepared became faster... and they didn't. The Double Dirty Bit was already sufficient, so there was no change.

That said, it is not entirely useless; if you create contrived test cases where rectangles are prone to "jitter," it was indeed 3–5 times faster. It is not a property you can just apply casually; you must understand the meaning of the property to use it effectively. In that sense, it is in the same category as will-change.

https://developer.mozilla.org/en-US/docs/Web/CSS/will-change

Future Plans

With a JS build of 80 KB (gzip) and a WASM build of around 130 KB (gzip), I have obtained the portable module I was looking for, regardless of standard compatibility. Since it should be a reusable module, I feel free to continue building a browser, create a library to replace Ink, or develop a TUI-based UI development environment using the Sixel rendering route.

Rather than strengthening the GUI, I am considering enhancing accessibility for AI and using the coordinate system for tasks like text extraction and related assistance.

While building this, I realized that layout engines and CSS style engines can actually be cleanly separated. If you are in control of the browser, you might not even need to generate the render tree from a format other than CSS. The expressive system of things like Cascading is constrained by the CSS format; for example, if you are optimizing for a 2D game engine, you could create a layout system with even stronger constraints.

Lastly, the best part of all this was that my understanding of how to think about browser optimizations and bottlenecks has improved by two levels through the implementation process. Everyone, go build a browser.

Discussion