Operational Steps
- 确认输入参数完整
- 执行核心操作(参考本目录下的 scripts/ 或 references/)
- 验证输出符合契约
- 保存结果并报告
Pitfalls
-
-
1.
2.
3.
version: 1.0.0
IO_CONTRACT
- input:
request: str, context: dict — 用户请求描述、上下文信息
- output:
result: dict — 技能执行结果(结构因技能而异)
对应原则:P2(机械原子暴露输入输出规范)
Pretext Creative Demos
Overview
@chenglou/pretext is a 15KB zero-dependency TypeScript library by Cheng Lou (React core, ReasonML, Midjourney) for DOM-free multiline text measurement and layout. It does one thing: given (text, font, width), return the line breaks, per-line widths, per-grapheme positions, and total height — all via canvas measurement, no reflow.
That sounds like plumbing. It is not. Because it is fast and geometric, it is a creative primitive: you can reflow paragraphs around a moving sprite at 60fps, build games whose level geometry is made of real words, drive ASCII logos through prose, shatter text into particles with exact per-grapheme starting positions, or pack shrink-wrapped multiline UI without any getBoundingClientRect thrash.
This skill exists so Hermes can make cool demos with it — the kind people post to X. See pretext.cool and chenglou.me/pretext for the community demo corpus.
When to Use
Use when the user asks for:
- A "pretext demo" / "cool pretext thing" / "text-as-X"
- Text flowing around a moving shape (hero sections, editorial layouts, animated long-form pages)
- ASCII-art effects using real words or prose, not monospace rasters
- Games where the playfield / obstacles / bricks are made of text (Tetris-from-letters, Breakout-of-prose)
- Kinetic typography with per-glyph physics (shatter, scatter, flock, flow)
- Typographic generative art, especially with non-Latin scripts or mixed scripts
- Multiline "shrink-wrap" UI (smallest container width that still fits the text)
- Anything that would require knowing line breaks before rendering
Don't use for:
- 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-video skills)
- Pure canvas generative art with no text role — use
p5js
Creative Standard
This is visual art rendered in a browser. Pretext returns numbers; you draw the thing.
- Don't ship a "hello world" demo. The
hello-orb-flow.html template is the starting point. Every delivered demo must add intentional color, motion, composition, and one visual detail the user didn't ask for but will appreciate.
- Dark backgrounds, warm cores, considered palette. Classic amber-on-black (CRT / terminal) works, but so do cold-white-on-charcoal (editorial) and desaturated pastels (risograph). Pick one and commit.
- Proportional fonts are the point. Pretext's whole vibe is "not monospaced" — lean into it. Use Iowan Old Style, Inter, JetBrains Mono, Helvetica Neue, or a variable font. Never default sans.
- Real source/text, not lorem ipsum. The corpus should mean something. Short manifestos, poetry, real source code, a found text, the library's own README — never
lorem ipsum.
- First-paint excellence. No loading states, no blank frames. The demo must look shippable the instant it opens.
Stack
Single self-contained HTML file per demo. No build step.
| Layer |
Tool |
Purpose |
| Core |
@chenglou/pretext via esm.sh CDN |
Text measurement + line layout |
| Render |
HTML5 Canvas 2D |
Glyph rendering, per-frame composition |
| Segmentation |
Intl.Segmenter (built-in) |
Grapheme splitting for emoji / CJK / combining marks |
| Interaction |
Raw DOM events |
Mouse / touch / wheel — no framework |
<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>
Pin the version. @0.0.6 at time of writing — check npm for the latest 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 (see references/patterns.md) 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 controls
write_file to a new .html in /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
prepareWithSegments is called with a bad font string; Intl.Segmenter is 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,
layoutNextLineRange in 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 into layoutNextLineRange before 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.font setting is surprisingly slow; set it once per frame if font doesn't vary, not per fillText call.
Common Pitfalls
Drifting CSS/canvas font strings. ctx.font = "16px Inter" measured, but CSS says font-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%. Always preload the font or use a web-safe family.
Re-preparing inside the animation loop. Only layout* is cheap. Re-calling prepare every frame will tank perf. Keep the prepared handle in module scope.
Forgetting Intl.Segmenter for grapheme splits. Emoji, combining marks, CJK — "é".split("") gives you two chars. Use new Intl.Segmenter(undefined, { granularity: "grapheme" }) when sampling individual visible glyphs.
break: 'never' chips without extraWidth. In rich-inline, if you use break: 'never' for an atomic chip/mention, you must also supply extraWidth for the pill padding — otherwise chip chrome overflows the container.
Using @chenglou/pretext from unpkg with TypeScript-only entry. Use esm.sh — it compiles the TS exports to browser-ready ESM automatically. unpkg will 404 or serve raw TS.
Monospace fallbacks silently erasing the whole point. Users seeing monospace-looking output often have a CSS font-family that fell through to monospace. 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 to layoutNextLineRange — 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
Reference: Community Demos
Clone these for inspiration / patterns (all MIT-ish, linked from pretext.cool):
验证清单 · VERIFICATION
约束规则 · RULES
- 输入约束: 参数类型、范围、格式必须校验
- 输出约束: 返回值结构、编码、命名必须一致
- 异常约束: 错误信息必须包含上下文和恢复建议
- 安全约束: 不执行未验证的任意代码,不暴露内部状态
Golden 集合 · GOLDEN SET
- Golden Input: 标准输入样本(覆盖正常路径)
- Golden Output: 预期输出(精确匹配或格式校验)
- Golden Error: 预期错误信息(覆盖失败路径)
Golden 集合是测试的单一真理来源。所有改进必须通过 golden 测试。
违反规则的操作视为不安全,必须拒绝或隔离。
每项验证必须可执行、可记录、可复现。验证失败时记录原因和修复。
- 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.
Pretext
Genes (策略基因)
紧凑策略表示。条件→策略。需要深度时参考完整文档。
- [PRET-001] 需要非矩形区域(如环绕移动物体)的文本布局 → 使用
layoutNextLineRange 配合每行动态宽度函数实现流式排版
- [PRET-002] 需要精确的字符级物理效果(如破碎、粒子化) → 使用
prepareWithSegments 获取每个字素(grapheme)的位置坐标
- [PRET-003] 需要计算多行文本的最小容器宽度(Shrink-wrap) → 使用
measureLineStats 获取最大行宽而非逐行渲染
- [PRET-004] 需要高性能遍历文本统计或物理模拟且无需字符串分配 → 使用
walkLineRanges 进行无字符串分配的迭代
- [PRET-005] 处理包含 Emoji、CJK 或组合标记的文本 → 使用
Intl.Segmenter 进行字素分割以确保测量准确性
- [PRET-006] 需要避免 DOM 重排(Reflow)导致的布局抖动 → 使用 Canvas 测量 API 在渲染前获取精确高度和换行信息
- [PRET-007] 构建单文件创意演示且无构建步骤 → 通过
esm.sh CDN 引入固定版本的 @chenglou/pretext 模块
1---2name: pretext3description: pretext4license: MIT5---678## Operational Steps91. 确认输入参数完整102. 执行核心操作(参考本目录下的 scripts/ 或 references/)113. 验证输出符合契约124. 保存结果并报告1314## Pitfalls15- 16- 171. 182. 193. 20version: 1.0.02122## IO_CONTRACT2324- **input**: `request: str, context: dict` — 用户请求描述、上下文信息25- **output**: `result: dict — 技能执行结果(结构因技能而异)`2627> 对应原则:P2(机械原子暴露输入输出规范)2829# Pretext Creative Demos3031## Overview3233[`@chenglou/pretext`](https://github.com/chenglou/pretext) is a 15KB zero-dependency TypeScript library by Cheng Lou (React core, ReasonML, Midjourney) for **DOM-free multiline text measurement and layout**. It does one thing: given `(text, font, width)`, return the line breaks, per-line widths, per-grapheme positions, and total height — all via canvas measurement, no reflow.3435That sounds like plumbing. It is not. Because it is fast and geometric, it is a **creative primitive**: you can reflow paragraphs around a moving sprite at 60fps, build games whose level geometry is made of real words, drive ASCII logos through prose, shatter text into particles with exact per-grapheme starting positions, or pack shrink-wrapped multiline UI without any `getBoundingClientRect` thrash.3637This skill exists so Hermes can make **cool demos** with it — the kind people post to X. See `pretext.cool` and `chenglou.me/pretext` for the community demo corpus.3839## When to Use4041Use when the user asks for:42- A "pretext demo" / "cool pretext thing" / "text-as-X"43- Text flowing around a moving shape (hero sections, editorial layouts, animated long-form pages)44- ASCII-art effects using **real words or prose**, not monospace rasters45- Games where the playfield / obstacles / bricks are made of text (Tetris-from-letters, Breakout-of-prose)46- Kinetic typography with per-glyph physics (shatter, scatter, flock, flow)47- Typographic generative art, especially with non-Latin scripts or mixed scripts48- Multiline "shrink-wrap" UI (smallest container width that still fits the text)49- Anything that would require knowing line breaks *before* rendering5051Don't use for:52- Static SVG/HTML pages where CSS already solves layout — just use CSS53- Rich text editors, general inline formatting engines (pretext is intentionally narrow)54- Image → text (use `ascii-art` / `ascii-video` skills)55- Pure canvas generative art with no text role — use `p5js`5657## Creative Standard5859This is visual art rendered in a browser. Pretext returns numbers; **you** draw the thing.6061- **Don't ship a "hello world" demo.** The `hello-orb-flow.html` template is the *starting* point. Every delivered demo must add intentional color, motion, composition, and one visual detail the user didn't ask for but will appreciate.62- **Dark backgrounds, warm cores, considered palette.** Classic amber-on-black (CRT / terminal) works, but so do cold-white-on-charcoal (editorial) and desaturated pastels (risograph). Pick one and commit.63- **Proportional fonts are the point.** Pretext's whole vibe is "not monospaced" — lean into it. Use Iowan Old Style, Inter, JetBrains Mono, Helvetica Neue, or a variable font. Never default sans.64- **Real source/text, not lorem ipsum.** The corpus should mean something. Short manifestos, poetry, real source code, a found text, the library's own README — never `lorem ipsum`.65- **First-paint excellence.** No loading states, no blank frames. The demo must look shippable the instant it opens.6667## Stack6869Single self-contained HTML file per demo. No build step.7071| Layer | Tool | Purpose |72|-------|------|---------|73| Core | `@chenglou/pretext` via `esm.sh` CDN | Text measurement + line layout |74| Render | HTML5 Canvas 2D | Glyph rendering, per-frame composition |75| Segmentation | `Intl.Segmenter` (built-in) | Grapheme splitting for emoji / CJK / combining marks |76| Interaction | Raw DOM events | Mouse / touch / wheel — no framework |7778```html79<script type="module">80import {81 prepare, layout, // use-case 1: simple height82 prepareWithSegments, layoutWithLines, // use-case 2a: fixed-width lines83 layoutNextLineRange, materializeLineRange, // use-case 2b: streaming / variable width84 measureLineStats, walkLineRanges, // stats without string allocation85} from "https://esm.sh/@chenglou/pretext@0.0.6";86</script>87```8889Pin the version. `@0.0.6` at time of writing — check [npm](https://www.npmjs.com/package/@chenglou/pretext) for the latest if demo behavior is off.9091## The Two Use Cases9293Almost everything reduces to one of these two shapes. Learn both.9495### Use-case 1 — measure, then render with CSS/DOM9697```js98const prepared = prepare(text, "16px Inter");99const { height, lineCount } = layout(prepared, 320, 20);100```101102You 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:103- Virtualized lists where rows contain wrapping text104- Masonry with precise card heights105- "Does this label fit?" dev-time checks106- Preventing layout shift when remote text loads107108**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.109110### Use-case 2 — measure *and* render yourself111112```js113const prepared = prepareWithSegments(text, FONT);114const { lines } = layoutWithLines(prepared, 320, 26);115for (let i = 0; i < lines.length; i++) {116 ctx.fillText(lines[i].text, 0, i * 26);117}118```119120This is where the creative work lives. You own the drawing, so you can:121- Render to canvas, SVG, WebGL, or any coordinate system122- Substitute per-glyph transforms (rotation, jitter, scale, opacity)123- Use line metadata (width, grapheme positions) as geometry124125For **variable-width-per-line** flow (text around a shape, text in a donut band, text in a non-rectangular column):126127```js128let cursor = { segmentIndex: 0, graphemeIndex: 0 };129let y = 0;130while (true) {131 const lineWidth = widthAtY(y); // your function: how wide is the corridor at this y?132 const range = layoutNextLineRange(prepared, cursor, lineWidth);133 if (!range) break;134 const line = materializeLineRange(prepared, range);135 ctx.fillText(line.text, leftEdgeAtY(y), y);136 cursor = range.end;137 y += lineHeight;138}139```140141This 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.142143### Helpers worth knowing144145- `measureLineStats(prepared, maxWidth)` → `{ lineCount, maxLineWidth }` — the widest line, i.e. multiline shrink-wrap width.146- `walkLineRanges(prepared, maxWidth, callback)` — iterate lines without allocating strings. Use for stats/physics over graphemes when you don't need the characters.147- `@chenglou/pretext/rich-inline` — the same system but for paragraphs mixing fonts / chips / mentions. Import from the subpath.148149## Demo Recipe Patterns150151The community corpus (see `references/patterns.md`) clusters into a handful of strong patterns. Pick one and riff — don't invent a new category unless asked.152153| Pattern | Key API | Example idea |154|---|---|---|155| **Reflow around obstacle** | `layoutNextLineRange` + per-row width function | Editorial paragraph that parts around a dragged cursor sprite |156| **Text-as-geometry game** | `layoutWithLines` + per-line collision rects | Breakout where each brick is a measured word |157| **Shatter / particles** | `walkLineRanges` → per-grapheme (x,y) → physics | Sentence that explodes into letters on click |158| **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 |159| **Editorial multi-column** | `layoutNextLineRange` per column + shared cursor | Animated magazine spread with pull quotes |160| **Kinetic type** | `layoutWithLines` + per-line transform over time | Star Wars crawl, wave, bounce, glitch |161| **Multiline shrink-wrap** | `measureLineStats` | Quote card that auto-sizes to its tightest container |162163See `templates/donut-orbit.html` and `templates/hello-orb-flow.html` for working single-file starters.164165## Workflow1661671. **Pick a pattern** from the table above based on the user's brief.1682. **Start from a template**:169 - `templates/hello-orb-flow.html` — text reflowing around a moving orb (reflow-around-obstacle pattern)170 - `templates/donut-orbit.html` — advanced example: measured ASCII logo obstacles, draggable wire sphere/cube, morphing shape fields, selectable DOM text, and dev-only controls171 - `write_file` to a new `.html` in `/tmp/` or the user's workspace.1723. **Swap the corpus** for something intentional to the brief. Real prose, 10-100 sentences, no lorem.1734. **Tune the aesthetic** — font, palette, composition, interaction. This is the work; don't skip it.1745. **Verify locally**:175 ```sh176 cd <dir-with-html> && python3 -m http.server 8765177 # then open http://localhost:8765/<file>.html178 ```1796. **Check the console** — pretext will throw if `prepareWithSegments` is called with a bad font string; `Intl.Segmenter` is available in every modern browser.1807. **Show the user the file path**, not just the code — they want to open it.181182## Performance Notes183184- `prepare()` / `prepareWithSegments()` is the expensive call. Do it **once** per text+font pair. Cache the handle.185- On resize, only rerun `layout()` / `layoutWithLines()` — never re-prepare.186- For per-frame animations where text doesn't change but geometry does, `layoutNextLineRange` in a tight loop is cheap enough to do every frame at 60fps for normal-length paragraphs.187- 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 into `layoutNextLineRange` before drawing text.188- 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.189- 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.190- Canvas `ctx.font` setting is surprisingly slow; set it **once** per frame if font doesn't vary, not per `fillText` call.191192## Common Pitfalls1931941. **Drifting CSS/canvas font strings.** `ctx.font = "16px Inter"` measured, but CSS says `font-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%. Always `preload` the font or use a web-safe family.1951962. **Re-preparing inside the animation loop.** Only `layout*` is cheap. Re-calling `prepare` every frame will tank perf. Keep the prepared handle in module scope.1971983. **Forgetting `Intl.Segmenter` for grapheme splits.** Emoji, combining marks, CJK — `"é".split("")` gives you two chars. Use `new Intl.Segmenter(undefined, { granularity: "grapheme" })` when sampling individual visible glyphs.1992004. **`break: 'never'` chips without `extraWidth`.** In `rich-inline`, if you use `break: 'never'` for an atomic chip/mention, you must also supply `extraWidth` for the pill padding — otherwise chip chrome overflows the container.2012025. **Using `@chenglou/pretext` from `unpkg` with TypeScript-only entry.** Use `esm.sh` — it compiles the TS exports to browser-ready ESM automatically. `unpkg` will 404 or serve raw TS.2032046. **Monospace fallbacks silently erasing the whole point.** Users seeing monospace-looking output often have a CSS `font-family` that fell through to `monospace`. Verify the actual rendered font via DevTools.2052067. **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 to `layoutNextLineRange` — pretext will return one-grapheme lines that look broken.2072088. **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."209210## Verification Checklist211212- [ ] Demo is a single self-contained `.html` file — opens by double-click or `python3 -m http.server`213- [ ] `@chenglou/pretext` imported via `esm.sh` with pinned version214- [ ] Corpus is real prose, not lorem ipsum, and matches the demo's concept215- [ ] Font string passed to `prepare` matches the CSS font exactly216- [ ] `prepare()` / `prepareWithSegments()` called once, not per frame217- [ ] Dark background + considered palette — not the default white canvas218- [ ] At least one interactive response (drag / hover / scroll / click) or idle auto-motion219- [ ] Tested locally with `python3 -m http.server` and confirmed no console errors220- [ ] 60fps on a mid-tier laptop (or graceful degradation documented)221- [ ] One "extra mile" detail the user didn't ask for222223## Reference: Community Demos224225Clone these for inspiration / patterns (all MIT-ish, linked from [pretext.cool](https://www.pretext.cool/)):226227## 验证清单 · VERIFICATION228229- [ ] Demo 为单个自包含 `.html`,无构建步骤,通过 `esm.sh` 引入固定版本(如 `@0.0.6`)的 `@chenglou/pretext`230- [ ] 传给 `prepare` 的 font 字符串与 CSS 实际渲染字体完全一致(避免 404 回退导致的测量漂移)231- [ ] `prepare()`/`prepareWithSegments()` 仅调用一次并缓存,动画循环中只重跑 `layout*`232- [ ] 文本 corpus 为真实内容(诗歌/代码/README 等),非 lorem ipsum,且与 demo 概念匹配233- [ ] 至少包含一个交互响应(drag/hover/scroll/click)或 idle 自动运动,且 `prepareWithSegments` 未因非法 font 字符串抛错234- [ ] 本地 `python3 -m http.server` 打开验证首帧无空白、无 console 错误,中端设备 60fps235236## 约束规则 · RULES2372381. **输入约束**: 参数类型、范围、格式必须校验2392. **输出约束**: 返回值结构、编码、命名必须一致2403. **异常约束**: 错误信息必须包含上下文和恢复建议2414. **安全约束**: 不执行未验证的任意代码,不暴露内部状态242243## Golden 集合 · GOLDEN SET244245- **Golden Input**: 标准输入样本(覆盖正常路径)246- **Golden Output**: 预期输出(精确匹配或格式校验)247- **Golden Error**: 预期错误信息(覆盖失败路径)248249> Golden 集合是测试的单一真理来源。所有改进必须通过 golden 测试。250251> 违反规则的操作视为不安全,必须拒绝或隔离。252253> 每项验证必须可执行、可记录、可复现。验证失败时记录原因和修复。254255- **Pretext Breaker** — breakout with word-bricks — `github.com/rinesh/pretext-breaker`256- **Tetris × Pretext** — `github.com/shinichimochizuki/tetris-pretext`257- **Dragon animation** — `github.com/qtakmalay/PreTextExperiments`258- **Somnai editorial engine** — `github.com/somnai-dreams/pretext-demos`259- **Bad Apple!! ASCII** — `github.com/frmlinn/bad-apple-pretext`260- **Drag-sprite reflow** — `github.com/dokobot/pretext-demo`261- **Alarmy editorial clock** — `github.com/SmisLee/alarmy-pretext-demo`262263Official playground: [chenglou.me/pretext](https://chenglou.me/pretext/) — accordion, bubbles, dynamic-layout, editorial-engine, justification-comparison, masonry, markdown-chat, rich-note.264265# Pretext266267## Genes (策略基因)268269> 紧凑策略表示。条件→策略。需要深度时参考完整文档。270271- **[PRET-001]** 需要非矩形区域(如环绕移动物体)的文本布局 → 使用 `layoutNextLineRange` 配合每行动态宽度函数实现流式排版272- **[PRET-002]** 需要精确的字符级物理效果(如破碎、粒子化) → 使用 `prepareWithSegments` 获取每个字素(grapheme)的位置坐标273- **[PRET-003]** 需要计算多行文本的最小容器宽度(Shrink-wrap) → 使用 `measureLineStats` 获取最大行宽而非逐行渲染274- **[PRET-004]** 需要高性能遍历文本统计或物理模拟且无需字符串分配 → 使用 `walkLineRanges` 进行无字符串分配的迭代275- **[PRET-005]** 处理包含 Emoji、CJK 或组合标记的文本 → 使用 `Intl.Segmenter` 进行字素分割以确保测量准确性276- **[PRET-006]** 需要避免 DOM 重排(Reflow)导致的布局抖动 → 使用 Canvas 测量 API 在渲染前获取精确高度和换行信息277- **[PRET-007]** 构建单文件创意演示且无构建步骤 → 通过 `esm.sh` CDN 引入固定版本的 `@chenglou/pretext` 模块