API reference
Short overview of common APIs—see package types and upstream docs for full behavior.
Use case 1: height only
import { prepare, layout } from '@chenglou/pretext'
const prepared = prepare('Hello', '16px Inter')
const { height, lineCount } = layout(prepared, 280, 24)- prepare(text, font, options?): font matches CanvasRenderingContext2D.font; optional { whiteSpace: 'pre-wrap' }.
- layout(prepared, maxWidth, lineHeight): returns height and line count.
Use case 2: line strings or varying widths
import {
prepareWithSegments,
layoutWithLines,
walkLineRanges,
layoutNextLine,
} from '@chenglou/pretext'
const p = prepareWithSegments(text, font)
const { lines, height, lineCount } = layoutWithLines(p, maxWidth, lineHeight)
walkLineRanges(p, maxWidth, (line) => {
// line.width, line.start, line.end
})
let cursor = { segmentIndex: 0, graphemeIndex: 0 }
for (;;) {
const line = layoutNextLine(p, cursor, widthForThisLine)
if (line === null) break
cursor = line.end
}Main types (conceptual)
- LayoutLine: text, width, start, end.
- LayoutCursor: segmentIndex, graphemeIndex.
Other helpers
- clearCache(): drop internal measurement caches (e.g. when swapping many fonts).
- setLocale(locale?): affects future prepare calls and clears cache.
- profilePrepare(...): timing breakdown for profiling.