Demos: https://chenglou.me/pretext/, https://somnai-dreams.github.io/pretext-demos/
This is incredibly impressive, many of this things have been missing for forever! I remember the first time I couldn't figure out how do a proper responsive accordion, it was with bootstrap 1, released in 2011 !! Today it's still not properly solved (until now?).
Many of thing things belong in css no in js, but this has been the pattern with so many things in the web
1) web needs evolve into more complex needs 2) hacky js/css implementation and workarounds 3) gets implemented as css standard
This is a not so hacky step 2. Really impressive,
I would have thunk that if this was actually possible someone would have done it already, apparently not, at some point I really want to understand what's the real insight in the library, their https://github.com/chenglou/pretext/blob/main/RESEARCH.md is interesting, they seem to have just done the hard work, of browser discrepancies to the last detail of what does an emoji measure in each browser, hope this is not a maintenance nightmare.
All in all this will push the web forward no doubt.
Building something like this was certainly possible before, but it was a lot of effort. What's changed is simple: AI. It seems clear this library was mostly built in Cursor using an agent. That's not a criticism, it's a perfect use of AI to build something that we couldn't before.
There's no reason why it couldn't have been built before. This is something that probably should exist as standard functionality, like what the Canvas API already includes. It's pretty basic functionality that every text renderer would include already at a lower level.
> This was achieved through showing Claude Code and Codex the browsers ground truth, and have them measure & iterate against those at every significant container width, running over weeks
https://x.com/_chenglou/status/2037715226838343871?s=20
There was another comment about using Autoresearch probably for this but I might be misremembering
This is something I've been thinking for ages and would love to add to Ensō (enso.sonnet.io), purely because it would allow me to apply better caret transitions between the lines of text.
(I'm not gonna do that because I'm trying to keep it simple, but it's a strong temptation)
Now a CSS tangent: regarding the accordion example from the site (https://chenglou.me/pretext/accordion), this can be solved with pure CSS (and then perhaps a JS fallback) using the `interpolate-size` property.
https://www.joshwcomeau.com/snippets/html/interpolate-size/
Regarding the text bubbles problem (https://chenglou.me/pretext/bubbles), you can use `text-wrap: balance | pretty` to achieve the same result.
(`balance` IIRC evens out the # of lines)
No, neither solves the problem. And even if `balance` did work, it's not a good substitute because you don't usually want your line lengths to all be the same length.
See also, related CSS Working Group issue: https://github.com/w3c/csswg-drafts/issues/191
Pretext makes this easier. Just pass the text and text properties (font, color, size, etc) into a pure JS API and it layouts the content into given viewport dimension.
Earlier you'll have to either use measureText or ship harbuzz to browser somehow. I guess pretext is not a technical breakthrough, just the right things assembled to make layouting as a pure JS API.
I have one question though: how is this different from Skia-wasm / Canvaskit? Skia already has sophisticated API to layout multiline text and it also is a pure algorithmic API.
When we’re using flutter, we’re asking for there to be a device-agnostic render-the-world API, i.e. Skia / Impeller.
Here, someone took the time to code with AI a pure Typescript version of glyph rendering.
For us, the difference would sort of be like the difference between having ffmpeg in Dart, and abstractly, having an ffmpeg C library.
It’s been technically possible for years to have a WASM/FFI version with a Dart API, but it hasn’t happened because it’s a lot to take on yourself, and “real companies” would just use a server, because once you’re charging for it, people expect things like backup, download links, their computer not to need to be awake for minutes to complete a transcode, etc
Neatly completing the analogy: now, you or I takes on the grunt work of getting this hammered out and tested via AI over the next two weeks, and sticks it on GitHub. It’s not necessarily the language choice or tool itself that’s fascinating, but it legitimately breaks new ground in client-side media FOSS just to have it possible at all
Edit: example: https://files.catbox.moe/4w3um0.png
It works, and still runs quite successfully in production, but there are still off-by-one hacks where I have no idea why they work. The iterative line generation feature here is huge.
Maybe for this we need a new web "Search" API instead of JS. Not sure it can be done otherwise without browser's help.
As far as I can tell, this went basically nowhere. Except this:
https://github.com/WICG/display-locking
https://developer.mozilla.org/en-US/docs/Web/API/Element/bef...
A browser API could help, but it would need to hook into selection, focus, scroll position, and match navigation across content the page has not rendered yet. That is a much bigger contract than 'search this string', and I would not bet on sites using it consistently.
That's why I've added Graphics.Text (https://docs.sciter.com/docs/Graphics/Text) in Sciter.
Graphics.Text is basically a detached <p> element that can be rendered on canvas with all CSS bells and whistles.
If you only perform layout once, it doesn't save any work. If you need to reflow many times, it saves a lot.
This thing isn't trying to do standard text layout faster than the browser, it's trying to enable more exotic/dynamic/custom layouts while keeping reasonable performance. Take a look at the demos linked in the repo's readme; those are things which the browser's layout engine can't do on its own.
Problem: DOM-based text measurement (getBoundingClientRect, offsetHeight) forces synchronous layout reflow. When components independently measure text, each measurement triggers a reflow of the entire document. This creates read/write interleaving that can cost 30ms+ per frame for 500 text blocks.
Solution: two-phase measurement centered around canvas measureText.
prepare(text, font) — segments text via Intl.Segmenter, measures each word via canvas, caches widths, and does one cached DOM calibration read per font when emoji correction is needed. Call once when text first appears.
layout(prepared, maxWidth, lineHeight) — walks cached word widths with pure arithmetic to count lines and compute height. Call on every resize. ~0.0002ms per text.
https://drafts.css-houdini.org/font-metrics-api-1/
RIP eae@.
The problem it solves is efficiently calculating the height of some wrapped text on a web page, without actually rendering that text to the page first (very expensive).
It does that by pre-calculating the width/height of individual segments - think words - and caching those. Then it implements the full algorithm for how browsers construct text strings by line-wrapping those segments using custom code.
This is absurdly hard because of the many different types of wrapping and characters (hyphenation, emoji, Chinese, etc) that need to be taken into account - plus the fact that different browsers (in particular Safari) have slight differences in their rendering algorithms.
It tests the resulting library against real browsers using a wide variety of long text documents, see https://github.com/chenglou/pretext/tree/main/corpora and https://github.com/chenglou/pretext/blob/main/pages/accuracy...
uWrap.js: https://news.ycombinator.com/item?id=43583478. it did not reach 11k stars overnight, tho :D
for ASCII text, mine finishes in 80ms, while pretext takes 2200ms. i haven't yet checked pretext for accuracy (how closely it matches the browser), but will test tonight - i expect it will do well.
let's see how close pretext can get to 80ms (or better) without adopting the same tricks.
https://github.com/chenglou/pretext/issues/18
there are already significant perf improvement PRs open right now, including one done using autoresearch.
That is to say, I wouldn't be so quick to call a library that only handles latin characters comparable to one that handles all this breath of things, and I also wouldn't be so quick to blame the performance delta on the assumption of greenfield AI-generated code.
internally it still uses the Canvas measureText() API, so there's nothing fundamentally that should differ unless Safari has broken measureText, which tbh, would not be out of character for that browser.
i think the intended purpose is that your text is maybe large but static and your layout just changes quickly. this is not the case for figuring out the height of 100k rows of different texts in a table, for example.
I am skeptical getting row height of many items only once is the intended behavior though. It is probably the intended behavior to get row height of many items and enables you to resizing width many time later (which is pretty useful on desktop).
It certainly seems to provide an API for analysing text layouts, but all of the computation still goes through the browser's native layout system.
Agreed! Text layout engines are stupidly hard. You start out thinking "It's a hard task, but I can do it" and then 3 months later you find yourself in a corner screaming "Why, Chinese? Why do you need to rotate your punctuation differently when you render in columns??"
This effort feeds back to the DOM, making it far more useful than my efforts which are confined to rendering multiline text on a canvas - for example: https://scrawl-v8.rikweb.org.uk/demo/canvas-206.html
(by the way, in your cool demo the wheel template can have some letter parts like the top of L or d extend beyond the wheel)
Yeah - I use the template (in that case, a circle) to calculate line lengths, then I run 2d text along the 1d lines. Even if I tried to keep all of the glyphs inside the wheel I'd fail - because some fonts lie about how tall they are. Fonts are, basically, criminals.
From the description, it doesn’t calculate it, but instead renders the segments in canvas and measures them. That’s still relatively slow compared to what native rendered-text-width APIs will do, and you have to hope that the browser’s rendering will use the identical logic in non-canvas contexts.
But in the end, in a browser, the actual text rendering is still done by the browser?
It's a library that allows to "do stuff" before the browser renders the actual text, but by still having the browser render, eventually, the actual text?
Or is this thing actually doing the final rendering of the text too?