AB
AiBoss
project

Pretext - an open-source AI front-end development tool that solves performance bottlenecks in Chinese character layout.

Pretext is an open-source, pure JavaScript/TypeScript multiline text measurement and layout library created by Cheng Lou, a former React core member. It is used to accurately measure the size of multiline text using pure arithmetic methods, completely bypassing DOM reflow.

What is Pretext?

Pretext is an open-source, pure JavaScript/TypeScript multiline text measurement and layout library developed by Cheng Lou, a former core React member. It's used for precise measurement of multiline text size using pure arithmetic, completely bypassing DOM reflow. Pretext employs a two-phase mechanism: prepare() Preprocess the text (word segmentation, Canvas measurement, caching). layout() Purely mathematical layout calculations. Pretext supports mixed language text, RTL, and emojis. It preprocesses 500 text segments in 19ms and calculates layouts in just 0.09ms. The tool is suitable for virtual scrolling, chat bubbles, magazine layouts, and AI-generated UI scenarios, allowing AI to obtain accurate layout data without needing to understand CSS.

Pretext's main functions

  • Zero DOM Reflow Text MeasurementBypass getBoundingClientRect When an API triggers a reflow, the text height and number of lines are obtained through pure mathematical calculations.
  • Two-stage architecture: prepare() One-time preprocessing (word segmentation + Canvas measurement + caching).layout() Purely arithmetic calculation layout, resulting in performance improvements of hundreds of times.
  • Full language support Supports complex layout scenarios such as mixed Chinese, Japanese, Arabic RTL, emoji, and soft hyphens.
  • Browser Differences Adaptation: Identify the special rendering behaviors of browsers such as Safari and render them as "true values" using an inverse fitting algorithm.
  • Multi-scenario Layout API It provides advanced features such as fixed-width line breaks, line-by-line routing (with support for dynamic width), and shrinkwrap.
  • Cross-platform rendering supportIt can output to DOM, Canvas, and SVG, and will soon support server-side rendering.

How to use Pretext

  • Installation IntroductionInstall via npm @chenglou/pretext Packages are used to import the necessary functions into the project.
  • Two-phase invocation:use prepare Perform one-time preprocessing on the text (including word segmentation, Canvas measurement, and result caching), then use... layout Perform pure arithmetic layout calculations; pass in the container width and line height to obtain the text height and number of lines.
  • Window adaptationWhen the container width changes (e.g., when the window resizes), simply call the function again. layoutNo need to repeat execution prepareMake full use of caching to improve performance.
  • Whitespace characters are reserved.When processing the content of a textarea class, in prepare Settings whiteSpace: 'pre-wrap' The option allows you to retain regular spaces, tabs, and newlines.
  • Fine layout control: Change prepareWithSegments Obtain segmented data, in conjunction with layoutWithLines To obtain the specific content of each line for Canvas/SVG rendering, or use... layoutNextLine Line-by-line processing supports mixed text and image layouts in scenarios with dynamic widths.
  • Cache managementWhen the application switches between a large number of fonts or text variations, call clearCache Release accumulated memory cache.

Key information and usage requirements of Pretext

  • Core positioningA pure JavaScript/TypeScript text measurement library that bypasses DOM reflow and uses pure arithmetic to calculate the height and layout of multi-line text.
  • Performance indicatorsBatch preprocessing of 500 text segments takes approximately 19ms, and subsequent layout calculations take only 0.09ms, which is hundreds of times faster than traditional DOM measurements.
  • Language supportFull language mixing (Chinese, Japanese, Arabic RTL, emoji), bidirectional text, soft hyphens, and browser compatibility.
  • Development BackgroundDeveloped by Cheng Lou, a former core React member, and completed after several weeks of iterations using Claude Code and Codex.
  • Applicable ScenariosVirtual scrolling, chat bubbles, waterfall/magazine layout, AI-generated UI (provides pure function interfaces; AI does not need to understand CSS)
  • Environmental requirementsSupports browser-side rendering (DOM/Canvas/SVG), and server-side rendering will be supported soon.
  • Font synchronization: Incoming font Parameters need to match CSS font Maintain consistency in the declaration (font size, font weight, style).
  • Avoid using system-uiThe font used on macOS may cause inaccurate measurements; it is recommended to use the specific font name.

Pretext's core advantages

  • Zero DOM reflowCompletely bypass getBoundingClientRect For APIs that trigger reordering, layout calculations do not block the main thread, thus avoiding performance bottlenecks.
  • Extreme speed performance500-segment text preprocessing takes 19ms, and subsequent layout takes only 0.09ms, hundreds of times faster than traditional DOM measurement, supporting 120fps scrolling and real-time adjustments.
  • Pure arithmetic calculationTransform text layout into a pure function: input content, font, width → output height and line position. AI can call it directly without understanding CSS.
  • Full language compatibilitySupports mixed text of Chinese and Arabic RTL, emoji, bidirectional text, and soft hyphens, and automatically adapts to browser differences (especially Safari).
  • Flexible outputThe calculation results can be rendered to DOM, Canvas, and SVG, supporting complex scenarios such as virtual scrolling, chat bubbles, magazine layout, and mixed text and images.

Pretext's project address

  • GitHub repositoryhttps://github.com/chenglou/pretext

Comparison of Pretext with similar products

Dimension Pretext Canvas measureText DOM measurement
Core Mechanism Canvas measurement + pure arithmetic line break algorithm + caching Browser native Canvas API Read the dimensions after actual rendering
Trigger rearrangement? Zero DOM Reflow No DOM manipulation Trigger Reordering
performance Extremely fast (layout time 0.09ms) Medium (manual line breaks required) Extremely slow (stuttering during batch measurements)
Multiline text support Built-in complete line break algorithm You need to implement it yourself. Browser automatic processing
Language support Full language support (including RTL and emoji) Basic support Native browser support
Difficulty of use Low (fully packaged) High (requires custom layout system) Low (simple API)
Applicable Scenarios Virtual scrolling, chat, AI-generated UI Canvas games, simple text Static pages, low-frequency measurements

Application scenarios of Pretext

  • Virtual scrolling/list optimizationThe tool knows the height of each line of text in advance, and can calculate the scroll position and visible area without rendering, achieving smooth scrolling at 120fps.
  • Chat/Message AppsThe tool can dynamically calculate the height of multi-line message bubbles, creating a "tight multiline bubble" layout to reduce wasted space.
  • Waterfall/Magazine LayoutFeatures include card height prediction, multi-column text flow, and mixed text and image layout with obstacle avoidance, enabling Pinterest-style layouts or complex editing pages.
  • AI Streaming OutputThe text height is calculated in real time when the large model is generated word by word to avoid content jumps and scroll position misalignment.