# Pretext Tutorial – Pure TS Text Measurement & Layout

**For the MikesBlogDesign team**  
Last updated: March 2026

Pretext is a tiny pure TypeScript library for multiline text measurement and layout **without touching the DOM**.

## Installation

```bash
npm install @chenglou/pretext
# or
bun add @chenglou/pretext
Core API
1. Basic Height Measurement (No DOM!)
TypeScriptimport { prepare, layout } from '@chenglou/pretext';

const text = "Your long content here...";
const font = "16px Inter";           // must match a font loaded on the page
const prepared = prepare(text, font);

const maxWidth = 400;
const lineHeight = 24;

const result = layout(prepared, maxWidth, lineHeight);
console.log(`Height: ${result.height}px | Lines: ${result.lineCount}`);
2. Preserve Whitespace (like textarea / accordion)
TypeScriptconst prepared = prepare(text, font, { whiteSpace: 'pre-wrap' });
const { height } = layout(prepared, width, lineHeight);
3. Manual Line Layout (for Canvas, SVG, rich text)
TypeScriptimport { prepareWithSegments, layoutWithLines } from '@chenglou/pretext';

const prepared = prepareWithSegments(text, font);
const { lines } = layoutWithLines(prepared, maxWidth, lineHeight);

lines.forEach(line => {
  // render line.text at line.x, line.y
});
4. Obstacle-Aware Text Flow (the magic feature)
TypeScriptlet cursor = { segmentIndex: 0, graphemeIndex: 0 };
let y = 0;

while (true) {
  const availableWidth = (y < imageBottomY) 
    ? columnWidth - imageWidth 
    : columnWidth;

  const line = layoutNextLine(prepared, cursor, availableWidth);
  if (!line) break;

  // render the line
  cursor = line.end;
  y += lineHeight;
}

## Team Next Steps

Clone the repo and explore the /demos folder locally (bun install && bun start)
Try the basic examples above in a new Astro component or playground
Build one small demo (accordion, chat bubbles, or masonry feed)
Share your experiment in the team channel

Official Resources

GitHub: https://github.com/chenglou/pretext
Live Demos: https://chenglou.me/pretext/
Community Demos: https://somnai-dreams.github.io/pretext-demos/

This Markdown file is the living tutorial. Update it anytime — the Astro page will always link here.