This thing is <i>very</i> impressive.<p>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).<p>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.<p>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.<p>It tests the resulting library against real browsers using a wide variety of long text documents, see <a href="https://github.com/chenglou/pretext/tree/main/corpora" rel="nofollow">https://github.com/chenglou/pretext/tree/main/corpora</a> and <a href="https://github.com/chenglou/pretext/blob/main/pages/accuracy.ts" rel="nofollow">https://github.com/chenglou/pretext/blob/main/pages/accuracy...</a>
i wrote something similar for this purpose, but much simpler and in 2kb, without AI, about a year ago.<p>uWrap.js: <a href="https://news.ycombinator.com/item?id=43583478">https://news.ycombinator.com/item?id=43583478</a>. it did <i>not</i> reach 11k stars overnight, tho :D<p>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.<p>let's see how close pretext can get to 80ms (or better) without adopting the same tricks.<p><a href="https://github.com/chenglou/pretext/issues/18" rel="nofollow">https://github.com/chenglou/pretext/issues/18</a><p>there are already significant perf improvement PRs open right now, including one done using autoresearch.
uWrap demo has text extending beyond text boxes all other the place on Safari, is that the price of simplicity?
Looks like uWrap only handles latin characters and doesn't deal with things like soft hyphens or emoji correction, plus uWrap only handles white-space: pre-line while Pretext doesn't handle pre-line but does handle both normal and pre-wrap.
correct, it was meant for estimating row height for virtualizing a 100k row table with a latin-ish LTR charset (no emoji handling, etc). its scope is much narrower. still, the difference in perf is significant, which i have found to be true in general of AI-generated geenfield code.
I've worked with text and in my experience all of these things (soft hyphens, emoji correction, non-latin languages, etc) are not exceptions you can easily incorporate later, but rather the rules that end up foundational parts of the codebase.<p>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.
There's a handful of perf related PRs open already so maybe it will be faster soon. I'm sure with enough focus on it we could have a hyper optimized version in a few hours.
prepare uses measure text, if it is in a for loop, it won't be fast. This library is meant to do prepare once and then layout many times. layout calls should be sub-1 ms.
it is not clear from the API/docs how i would use prepare() once on one text and then use layout() for completely different text.<p>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 think for that to use pretext is to join each row with hard line break and then do prepare once, then walk each line. At least that will put the single layout performance into the best light.<p>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).
> This thing is very impressive.<p>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??"<p>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: <a href="https://scrawl-v8.rikweb.org.uk/demo/canvas-206.html" rel="nofollow">https://scrawl-v8.rikweb.org.uk/demo/canvas-206.html</a>
I had struggled so much to measure text and number of lines when creating dynamic subtitles for remotion videos, not sure if it was my incompetence or a complexity with the DOM itself. I feel hopeful this will make it much easier :-)
> 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).<p>But in the end, in a browser, the actual text rendering is still done by the browser?<p>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?<p>Or is this thing actually doing the final rendering of the text too?
I said it elsewhere but will repeat it here:<p>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?).<p>Many of thing things belong in css no in js, but this has been the pattern with so many things in the web<p>1) web needs evolve into more complex needs
2) hacky js/css implementation and workarounds
3) gets implemented as css standard<p>This is a not so hacky step 2. Really impressive,<p>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 <a href="https://github.com/chenglou/pretext/blob/main/RESEARCH.md" rel="nofollow">https://github.com/chenglou/pretext/blob/main/RESEARCH.md</a> 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.<p>All in all this will push the web forward no doubt.
Responsive accordions are actually solved using CSS nowadays, but plenty of other things aren't, and the web has definitely needed an API or library like this for a long, long time. So it's great that we now have it.<p>Building something like this was certainly <i>possible</i> 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.
> it's a perfect use of AI to build something that we couldn't before.<p>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.
Love this. I especially liked shape based reflow example.<p>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.<p>(I'm not gonna do that because I'm trying to keep it simple, but it's a strong temptation)<p>Now a CSS tangent: regarding the accordion example from the site (<a href="https://chenglou.me/pretext/accordion" rel="nofollow">https://chenglou.me/pretext/accordion</a>), this can be solved with pure CSS (and then perhaps a JS fallback) using the `interpolate-size` property.<p><a href="https://www.joshwcomeau.com/snippets/html/interpolate-size/" rel="nofollow">https://www.joshwcomeau.com/snippets/html/interpolate-size/</a><p>Regarding the text bubbles problem (<a href="https://chenglou.me/pretext/bubbles" rel="nofollow">https://chenglou.me/pretext/bubbles</a>), you can use `text-wrap: balance | pretty` to achieve the same result.<p>(`balance` IIRC evens out the # of lines)
> Regarding the text bubbles problem [...], you can use `text-wrap: balance | pretty` to achieve the same result.<p>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.<p>See also, related CSS Working Group issue: <a href="https://github.com/w3c/csswg-drafts/issues/191" rel="nofollow">https://github.com/w3c/csswg-drafts/issues/191</a>
text-wrap can help to balance out the number of words per line, but it still doesn’t eliminate the extra empty space on the right edge of the box.
Quick overview of pretext: if you want to layout text on the web, you have to use canvas.measureText API and implement line-breaking / segmentation / RTL yourself.<p>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.<p>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.<p>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.
> how is this different from Skia-wasm<p>It’s not wasm?
If the author is right, this is going to be huge for GUI web frameworks and for future rich text editors.
Skia brings in the world. You’re not wrong, and I understand the subtleties in the Q you asked (i.e. we’re talking Flutter; peer comment saying Skia-wasm is wasm comes across as pedantry to us because wasm vs JS is a compile-time option).<p>When we’re using flutter, we’re asking for there to be a device-agnostic render-the-world API, i.e. Skia / Impeller.<p>Here, someone took the time to code with AI a pure Typescript version of glyph rendering.<p>For us, the difference would sort of be like the difference between having ffmpeg in Dart, and abstractly, having an ffmpeg C library.<p>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<p>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 <i>just to have it possible at all</i>
By the author of the library<p>> 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<p><a href="https://x.com/_chenglou/status/2037715226838343871?s=20" rel="nofollow">https://x.com/_chenglou/status/2037715226838343871?s=20</a><p>There was another comment about using Autoresearch probably for this but I might be misremembering
Gosh, I wish this had existed a year ago; I spent an absurd amount of time creating a system for print brochure typesetting in HTML, that would iteratively try to find viable break points (keeping in mind that bullets etc. could exist at any time) that would ensure non-orphaned new lines, etc., all by using the Selection API and repeatedly finding bounding boxes of prospective renders.<p>It works, and still runs quite successfully in production, but there are still off-by-one hacks where I have no idea <i>why</i> they work. The iterative line generation feature here is <i>huge</i>.
With all the multi$ efforts invested in the browsers, what explains that such basics as text layout are neglected, requiring libraries such as this one?
This should be standard functionality offered by browsers. How do you make feature requests to W3C, and do they allow the community to vote on feature ideas?
The proposal already exists [1], but vendors would need to agree to both prioritize and ship it.<p>Right now Chrome is much more focused on AI related APIs (sigh) and not stuff like FontMetrics.<p>[1] <a href="https://drafts.css-houdini.org/font-metrics-api-1/" rel="nofollow">https://drafts.css-houdini.org/font-metrics-api-1/</a>
Has someone ever found a good solution for long / infinite lists / grids virtualization not breaking browsers native text search?<p>Maybe for this we need a new web "Search" API instead of JS. Not sure it can be done otherwise without browser's help.
<a href="https://wicg.github.io/virtual-scroller/#find-in-page-apis" rel="nofollow">https://wicg.github.io/virtual-scroller/#find-in-page-apis</a><p>As far as I can tell, this went basically nowhere. Except this:<p><a href="https://github.com/WICG/display-locking" rel="nofollow">https://github.com/WICG/display-locking</a><p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/beforematch_event" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/API/Element/bef...</a>
Hm, the demos all render wrong on my system (Fedora, Firefox). The torus for example is completely distorted.<p>Edit: example: <a href="https://files.catbox.moe/4w3um0.png" rel="nofollow">https://files.catbox.moe/4w3um0.png</a>
The FontMetrics API solves this, hopefully browsers will ship it someday.<p><a href="https://drafts.css-houdini.org/font-metrics-api-1/" rel="nofollow">https://drafts.css-houdini.org/font-metrics-api-1/</a><p>RIP eae@.
The most practical use case is the text bubble wrapping one. That’s always frustrating when you want to wrap text inside any box with a border or background color (like a button or a “badge” component).
Yeah, that's definitely needed.<p>That's why I've added Graphics.Text (<a href="https://docs.sciter.com/docs/Graphics/Text" rel="nofollow">https://docs.sciter.com/docs/Graphics/Text</a>) in Sciter.<p>Graphics.Text is basically a detached <p> element that can be rendered on canvas with all CSS bells and whistles.
This is awesome! I had this problem when building a datagrid where cells would dynamically render textarea. IIRC I ended up doing a simple canvas measurement, but I had all the text and font properties static, and even then it was hellish to get it right.
I've had to approximate text size without rendering it a few times and it's always been awkward, I'm glad there's something to reach for now (just hoping I remember that this exists next time I need it)
Some details on how it works from a code comment:<p>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.<p>Solution: two-phase measurement centered around canvas measureText.<p>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.<p>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.<p><a href="https://github.com/chenglou/pretext/blob/main/src/layout.ts" rel="nofollow">https://github.com/chenglou/pretext/blob/main/src/layout.ts</a>
Regardless of the subject matter, the tweets announcing this are a masterclass in demoing why an architectural/platform improvement can be impactful.
only took 30+ years to get (back) to this point.<p>wasted generation.
[dead]