Pretext Skill: Build Creative Browser Demos with DOM-Free Text Layout
Build creative browser demos with DOM-free text layout.
Written by Neura Market from the official Hermes Agent documentation for Pretext. Commands, paths, and version numbers are reproduced from the source unchanged.
Read the official documentationPretext is a 15KB zero-dependency TypeScript library by Cheng Lou (React core, ReasonML, Midjourney) for DOM-free multiline text measurement and layout. It takes text, a font string, and a width, then returns line breaks, per-line widths, per-grapheme positions, and total height, all via canvas measurement, no reflow. This skill packages it for Hermes Agent so you can build browser demos that reflow paragraphs around moving sprites at 60fps, turn prose into game geometry, drive ASCII logos with real text, shatter words into particles, or pack shrink-wrapped multiline UI without DOM reads.
What it does
Pretext gives you exact geometric information about how text will break and render at a given width, without ever touching the DOM. That makes it a creative primitive: you can animate text around obstacles, build typographic games, generate kinetic typography with per-glyph physics, or create ASCII art from proportional fonts. The library is fast enough to run layout every frame at 60fps for normal paragraphs, and it handles non-Latin scripts, emoji, and mixed scripts via Intl.Segmenter.
Before you start
- Skill path:
skills/creative/pretext - Version: 1.0.0
- License: MIT
- Platforms: linux, macos, windows
- Prerequisites: A modern browser (Chrome, Firefox, Safari, Edge) with
Intl.Segmentersupport. No build step, each demo is a single self-contained HTML file. - Installation: This skill is bundled with Hermes Agent and installed by default. No additional setup required.
- Related skills: p5js, claude-design, excalidraw, architecture-diagram
Import and setup
Every demo starts by importing Pretext from the esm.sh CDN. Pin the version to avoid breaking changes.
<script type="module">
import {
prepare, layout, // use-case 1: simple height
prepareWithSegments, layoutWithLines, // use-case 2a: fixed-width lines
layoutNextLineRange, materializeLineRange, // use-case 2b: streaming / variable width
measureLineStats, walkLineRanges, // stats without string allocation
} from "https://esm.sh/@chenglou/pretext@0.0.6";
</script>
Check npm for the latest version if demo behavior is off.
The two use cases
Almost everything reduces to one of these two shapes. Learn both.
Use-case 1, measure, then render with CSS/DOM
const prepared = prepare(text, "16px Inter");
const { height, lineCount } = layout(prepared, 320, 20);
You still let the browser draw the text. Pretext just tells you how tall the box will be at a given width, without a DOM read. Use for:
- Virtualized lists where rows contain wrapping text
- Masonry with precise card heights
- "Does this label fit?" dev-time checks
- Preventing layout shift when remote text loads
Keep font and letterSpacing exactly in sync with your CSS. The canvas ctx.font format (e.g. "16px Inter", "500 17px 'JetBrains Mono'") must match the rendered CSS, or measurements drift.
Use-case 2, measure and render yourself
const prepared = prepareWithSegments(text, FONT);
const { lines } = layoutWithLines(prepared, 320, 26);
for (let i = 0; i < lines.length; i++) {
ctx.fillText(lines[i].text, 0, i * 26);
}
This is where the creative work lives. You own the drawing, so you can:
- Render to canvas, SVG, WebGL, or any coordinate system
- Substitute per-glyph transforms (rotation, jitter, scale, opacity)
- Use line metadata (width, grapheme positions) as geometry
For variable-width-per-line flow (text around a shape, text in a donut band, text in a non-rectangular column):
let cursor = { segmentIndex: 0, graphemeIndex: 0 };
let y = 0;
while (true) {
const lineWidth = widthAtY(y); // your function: how wide is the corridor at this y?
const range = layoutNextLineRange(prepared, cursor, lineWidth);
if (!range) break;
const line = materializeLineRange(prepared, range);
ctx.fillText(line.text, leftEdgeAtY(y), y);
cursor = range.end;
y += lineHeight;
}
This is the most important pattern in the whole library. It's what unlocks "text flowing around a dragged sprite", the demo that went viral on X.
Helpers worth knowing
measureLineStats(prepared, maxWidth)→{ lineCount, maxLineWidth }, the widest line, i.e. multiline shrink-wrap width.walkLineRanges(prepared, maxWidth, callback), iterate lines without allocating strings. Use for stats/physics over graphemes when you don't need the characters.@chenglou/pretext/rich-inline, the same system but for paragraphs mixing fonts / chips / mentions. Import from the subpath.
Demo recipe patterns
The community corpus clusters into a handful of strong patterns. Pick one and riff, don't invent a new category unless asked.
| Pattern | Key API | Example idea |
|---|---|---|
| Reflow around obstacle | layoutNextLineRange + per-row width function | Editorial paragraph that parts around a dragged cursor sprite |
| Text-as-geometry game | layoutWithLines + per-line collision rects | Breakout where each brick is a measured word |
| Shatter / particles | walkLineRanges → per-grapheme (x,y) → physics | Sentence that explodes into letters on click |
| ASCII obstacle typography | layoutNextLineRange + measured per-row obstacle spans | Bitmap ASCII logo, shape morphs, and draggable wire objects that make text open around their actual geometry |
| Editorial multi-column | layoutNextLineRange per column + shared cursor | Animated magazine spread with pull quotes |
| Kinetic type | layoutWithLines + per-line transform over time | Star Wars crawl, wave, bounce, glitch |
| Multiline shrink-wrap | measureLineStats | Quote card that auto-sizes to its tightest container |
See templates/donut-orbit.html and templates/hello-orb-flow.html for working single-file starters.
Workflow
-
Pick a pattern from the table above based on the user's brief.
-
Start from a template:
templates/hello-orb-flow.html, text reflowing around a moving orb (reflow-around-obstacle pattern)templates/donut-orbit.html, advanced example: measured ASCII logo obstacles, draggable wire sphere/cube, morphing shape fields, selectable DOM text, and dev-only controlswrite_fileto a new.htmlin/tmp/or the user's workspace.
-
Swap the corpus for something intentional to the brief. Real prose, 10-100 sentences, no lorem.
-
Tune the aesthetic, font, palette, composition, interaction. This is the work; don't skip it.
-
Verify locally:
cd <dir-with-html> && python3 -m http.server 8765
# then open http://localhost:8765/<file>.html
- Check the console, pretext will throw if
prepareWithSegmentsis called with a bad font string;Intl.Segmenteris available in every modern browser. - Show the user the file path, not just the code, they want to open it.
Performance notes
prepare()/prepareWithSegments()is the expensive call. Do it once per text+font pair. Cache the handle.- On resize, only rerun
layout()/layoutWithLines(), never re-prepare. - For per-frame animations where text doesn't change but geometry does,
layoutNextLineRangein a tight loop is cheap enough to do every frame at 60fps for normal-length paragraphs. - When rendering ASCII masks per frame, keep a cell buffer (
Uint8Array/typed arrays), derive measured per-row obstacle spans from the cells or projected geometry, merge spans, then feed those spans intolayoutNextLineRangebefore drawing text. - Keep visual animation and layout animation coupled. If a sphere morphs into a cube, tween both the rendered cell buffer and the obstacle spans with the same value; otherwise the demo looks painted-on instead of physically reflowed.
- For fades, prefer layer opacity over changing glyph intensity or obstacle scale. Put transient ASCII sprites on their own canvas and fade the canvas with CSS/GSAP opacity so geometry does not appear to shrink.
- Canvas
ctx.fontsetting is surprisingly slow; set it once per frame if font doesn't vary, not perfillTextcall.
Common pitfalls
- Drifting CSS/canvas font strings.
ctx.font = "16px Inter"measured, but CSS saysfont-family: Inter, sans-serif; font-size: 16px. Fine if Inter loads. If Inter 404s, CSS falls back to sans-serif and measurements drift by 5-20%. Alwayspreloadthe font or use a web-safe family. - Re-preparing inside the animation loop. Only
layout*is cheap. Re-callingprepareevery frame will tank perf. Keep the prepared handle in module scope. - Forgetting
Intl.Segmenterfor grapheme splits. Emoji, combining marks, CJK,"é".split("")gives you two chars. Usenew Intl.Segmenter(undefined, { granularity: "grapheme" })when sampling individual visible glyphs. break: 'never'chips withoutextraWidth. Inrich-inline, if you usebreak: 'never'for an atomic chip/mention, you must also supplyextraWidthfor the pill padding, otherwise chip chrome overflows the container.- Using
@chenglou/pretextfromunpkgwith TypeScript-only entry. Useesm.sh, it compiles the TS exports to browser-ready ESM automatically.unpkgwill 404 or serve raw TS. - Monospace fallbacks silently erasing the whole point. Users seeing monospace-looking output often have a CSS
font-familythat fell through tomonospace. Verify the actual rendered font via DevTools. - Skipping rows vs adjusting width when flowing around a shape. If the corridor on this row is too narrow to fit a line, skip the row (
y += lineHeight; continue;) rather than passing a tiny maxWidth tolayoutNextLineRange, pretext will return one-grapheme lines that look broken. - Shipping a cold demo. The default first-paint looks tutorial-grade. Add: vignette, subtle scanline, idle auto-motion, one carefully chosen interactive response (drag, hover, scroll, click). Without these, "cool pretext demo" lands as "intern repro of the README."
Verification checklist
- Demo is a single self-contained
.htmlfile, opens by double-click orpython3 -m http.server @chenglou/pretextimported viaesm.shwith pinned version- Corpus is real prose, not lorem ipsum, and matches the demo's concept
- Font string passed to
preparematches the CSS font exactly prepare()/prepareWithSegments()called once, not per frame- Dark background + considered palette, not the default white canvas
- At least one interactive response (drag / hover / scroll / click) or idle auto-motion
- Tested locally with
python3 -m http.serverand confirmed no console errors - 60fps on a mid-tier laptop (or graceful degradation documented)
- One "extra mile" detail the user didn't ask for
When not to use it
- Static SVG/HTML pages where CSS already solves layout, just use CSS
- Rich text editors, general inline formatting engines (pretext is intentionally narrow)
- Image → text (use
ascii-art/ascii-videoskills) - Pure canvas generative art with no text role, use
p5js
Limits and gotchas
- Pretext returns numbers; you draw the thing. It is not a rendering library.
- The library is intentionally narrow, it does one thing (text measurement and layout) and does not handle rich text formatting, inline images, or complex styling.
- Font loading is critical: if the font specified in
ctx.fontdoes not load, the browser falls back to a default, and measurements drift. - The
rich-inlinesubpath requires careful handling ofbreak: 'never'chips withextraWidth. - Always use
esm.shfor import;unpkgwill not work because the package exports TypeScript.
What pairs with this
- p5js, for pure canvas generative art when text is not the focus
- claude-design, for UI/UX design tasks that may benefit from measured text
- excalidraw, for hand-drawn style diagrams with text
- architecture-diagram, for system diagrams that need precise text layout
Clone these for inspiration / patterns (all MIT-ish, linked from pretext.cool):
- Pretext Breaker, breakout with word-bricks,
github.com/rinesh/pretext-breaker - Tetris × Pretext,
github.com/shinichimochizuki/tetris-pretext - Dragon animation,
github.com/qtakmalay/PreTextExperiments - Somnai editorial engine,
github.com/somnai-dreams/pretext-demos - Bad Apple!! ASCII,
github.com/frmlinn/bad-apple-pretext - Drag-sprite reflow,
github.com/dokobot/pretext-demo - Alarmy editorial clock,
github.com/SmisLee/alarmy-pretext-demo
Official playground: chenglou.me/pretext, accordion, bubbles, dynamic-layout, editorial-engine, justification-comparison, masonry, markdown-chat, rich-note.