pretext icon indicating copy to clipboard operation
pretext copied to clipboard

layout() returns height: 0 for empty string — browser renders 1 × lineHeight

Open beeegee opened this issue 7 months ago • 1 comments

Bug description

layout(prepare(""), maxWidth, lineHeight) returns { lineCount: 0, height: 0 } for an empty string. But a browser renders an empty block element at lineHeight height — the element still occupies one line even when its text content is empty.

Reproduction

import { prepare, layout } from '@chenglou/pretext'

const empty = prepare('', '16px Inter')
const { lineCount, height } = layout(empty, 400, 20)
console.log(lineCount, height)  // → 0, 0

// Browser reference:
// <div style="font: 16px Inter; line-height: 20px"></div>
// getBoundingClientRect().height === 20   (not 0)

Why it matters

Any consumer that uses Pretext to size a container — chat bubbles, textarea wrappers, virtual list items — gets a collapsed zero-height box for empty content. The workaround is Math.max(1, lineCount) * lineHeight, but this is nowhere documented and easy to miss.

Contrast with the pre-wrap whitespace-only case, where prepare(' ', font, { whiteSpace: 'pre-wrap' }) correctly returns lineCount: 1 because the spaces are preserved. The empty-string case has no parallel workaround documented.

What the library could do

Two options:

  1. Document it in the README — add a note under layout() that empty text returns { lineCount: 0, height: 0 } and show the Math.max(1, lineCount) pattern. Safest option, zero breaking change.

  2. Change the semantics — treat empty text as 1 line (matches browser). This would be a breaking change for any caller that currently relies on lineCount === 0 to detect empty strings.

Option 1 seems safer given existing callers.

beeegee avatar Apr 08 '26 06:04 beeegee

Fixed in #118 — went with Option 1 (docs only). Added a callout under layout() in the README explaining the { lineCount: 0, height: 0 } behavior and showing the Math.max(1, lineCount) * lineHeight pattern for container-sizing callers.

beeegee avatar Apr 08 '26 10:04 beeegee