6 ms·
Pretext: TypeScript library for multiline text measurement and layout
https://x.com/_chenglou/status/2037713766205608234 https://x.com/_chenglou/status/2037713766205608234, https://xcancel.com/_chenglou/status/2037713766205608234 https://xcancel.com/_chenglou/status/2037713766205608234
Demos: https://chenglou.me/pretext/ https://chenglou.me/pretext/, https://somnai-dreams.github.io/pretext-demos/ https://somnai-dreams.github.io/pretext-demos/
https://kevinho.com/experiments/biomap/ https://kevinho.com/experiments/biomap/
- rattray 7mo agoRegardless of the subject matter, the tweets announcing this are a masterclass in demoing why an architectural/platform improvement can be impactful.
- rattray 7mo agoSome details on how it works from a code comment: 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://github.com/chenglou/pretext/blob/main/src/layout.ts https://github.com/chenglou/pretext/blob/main/src/layout.ts
- gastonmorixe 7mo agoHas someone ever found a good solution for long / infinite lists / grids virtualization not breaking browsers native text search? Maybe for this we need a new web "Search" API instead of JS. Not sure it can be done otherwise without browser's help.
- incr_me 7mo agohttps://wicg.github.io/virtual-scroller/#find-in-page-apis https://wicg.github.io/virtual-scroller/#find-in-page-apis As far as I can tell, this went basically nowhere. Except this: https://github.com/WICG/display-locking https://github.com/WICG/display-locking https://developer.mozilla.org/en-US/docs/Web/API/Element/beforematch_event https://developer.mozilla.org/en-US/docs/Web/API/Element/bef...
- gastonmorixe 6mo agovery interesting! thank you for those links
- hrmtst93837 7mo ago[flagged]
- righthand 7mo agoLol improving the DOM and HTML instead of just tossing it into JS? WHATWG will be rolling on the floor for days.
- dalmo3 7mo agoThis 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.
- rpastuszak 7mo agoLove this. I especially liked shape based reflow example. 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 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/ https://www.joshwcomeau.com/snippets/html/interpolate-size/ Regarding the text bubbles problem (https://chenglou.me/pretext/bubbles https://chenglou.me/pretext/bubbles), you can use `text-wrap: balance | pretty` to achieve the same result. (`balance` IIRC evens out the # of lines)
- dnlzro 7mo ago> Regarding the text bubbles problem [...], you can use `text-wrap: balance | pretty` to achieve the same result. 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 https://github.com/w3c/csswg-drafts/issues/191
- rpastuszak 7mo agoHa, I didn't know about that, I stand corrected, thanks!
- tshaddox 7mo agotext-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.
- lewisjoe 7mo agoQuick 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. 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.
- lewisjoe 7mo agoIf the author is right, this is going to be huge for GUI web frameworks and for future rich text editors.
- madeofpalk 7mo ago> how is this different from Skia-wasm It’s not wasm?
- refulgentis 7mo agoSkia 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). 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
- simonw 7mo agoThis thing is very impressive. 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 https://github.com/chenglou/pretext/tree/main/corpora and https://github.com/chenglou/pretext/blob/main/pages/accuracy.ts https://github.com/chenglou/pretext/blob/main/pages/accuracy...
- jimkleiber 7mo agoI 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 :-)
- rikroots 7mo ago> This thing is very impressive. 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 https://scrawl-v8.rikweb.org.uk/demo/canvas-206.html
- eviks 7mo agoWhy do you bring up Chinese cornes if the basic Latin text in the Pretext demo is deficient? (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)
- Trufa 7mo agoI said it elsewhere but will repeat it here: 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 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.
- staminade 7mo agoResponsive 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. 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.
- Rohansi 7mo ago> 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.
- deleted 7mo ago[deleted]
- c-smile 7mo agoYeah, that's definitely needed. That's why I've added Graphics.Text (https://docs.sciter.com/docs/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.
- lateforwork 7mo agoThis 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?
- esprehn 7mo agoThe proposal already exists [1], but vendors would need to agree to both prioritize and ship it. Right now Chrome is much more focused on AI related APIs (sigh) and not stuff like FontMetrics. [1] https://drafts.css-houdini.org/font-metrics-api-1/ https://drafts.css-houdini.org/font-metrics-api-1/
- siriusfeynman 7mo agoI'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)
- gjvc 7mo agoonly took 30+ years to get (back) to this point. wasted generation.
- Retr0id 7mo agoHm, the demos all render wrong on my system (Fedora, Firefox). The torus for example is completely distorted. Edit: example: https://files.catbox.moe/4w3um0.png https://files.catbox.moe/4w3um0.png
- Retr0id 7mo agoI think it goes to show, if you try to make something like this you'll be chasing a long tail of edge cases ~forever.
- deleted 7mo ago[deleted]
- pugchat 7mo ago[dead]
- smusamashah 7mo agoBy the author of the library > 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 https://x.com/_chenglou/status/2037715226838343871?s=20 There was another comment about using Autoresearch probably for this but I might be misremembering
- madrox 6mo agoThis feels like a great example of a project that wouldn't exist if not for AI coding.
- btown 7mo agoGosh, 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. 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.
- esprehn 7mo agoThe FontMetrics API solves this, hopefully browsers will ship it someday. https://drafts.css-houdini.org/font-metrics-api-1/ https://drafts.css-houdini.org/font-metrics-api-1/ RIP eae@.
- tshaddox 7mo agoThe 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).
- eviks 7mo agoWith all the multi$ efforts invested in the browsers, what explains that such basics as text layout are neglected, requiring libraries such as this one?
- richardw 7mo agoI did ~this in the 200X’s for a C# todo list, not nearly as polished but it was still So Much Work. Filed under things that should just work already.
- slopinthebag 7mo agoI get the feeling this is an AI hallucination. It uses the canvas to render the text to be measured, which doesn't bypass the browser layouting. The only potential performance to be gained here is rendering straight to a canvas instead of building a dom node, but it's not clear that it's actually faster. I can't imagine the cost of a single <p> is that large, and I'm not certain that it's slower than whatever steps the canvas API uses to turn text into pixels.
- sethaurus 7mo agoWhat you're missing is that each segment (typically a word) only needs to be measured once, in the setup phase. The canvas gets thrown away after that, and subsequent layout passes all reuse the cached measurements. If you only perform layout once, it doesn't save any work. If you need to reflow many times, it saves a lot.
- slopinthebag 6mo agoAre you sure the browser doesn't similarly cache it's own layout calculations?
- sethaurus 6mo agoI'm sure the browser does do that, and plenty of other optimisations too! 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.
- voidUpdate 7mo agoI was just writing a long comments about how the "const prepared = prepare('AGI 春天到了. بدأت الرحلة ', '16px Inter')" example makes no sense, as the font name is weirdly split across both arguments, but theres some right-to-left stuff going on. The font is "16px Inter", and the arabic and emoji are part of the first argument
- TheProfitKing 7mo ago[dead]
- joey5403 6mo agoI saw this amazing project in the news yesterday, and I've already implemented it on my personal blog today.
- nmr521521 6mo agoI've also started using it, made a small game, and the project has turned out really well. I'll try more application scenarios in the future. https://pretext.lol https://pretext.lol
- frankezene 6mo ago[dead]