Skip to content

@jsvision/ui / wrapText

Function: wrapText()

wrapText(content, width): string[]

Defined in: ui/src/controls/measure.ts:108

Word-wrap content to width display columns — the same wrapping a Text view applies when it draws. Reach for it when you need the line count before laying anything out, e.g. to size a dialog tall enough that its message cannot be clipped.

Each output line is a verbatim slice of the source, so whitespace between words and leading indentation are preserved, not collapsed. The wrap breaks after the last whole word that fits; a single word wider than the view is hard-broken at the width boundary; the spaces at a break are dropped from the start of the next line. An explicit \n always forces a line break, and a blank source line stays a blank output line. A width of zero or less yields no lines at all.

Widths are measured in display columns rather than characters, so wide CJK glyphs wrap where they actually render instead of where String.length would guess. A glyph too wide to ever fit — a 2-column character at width 1 — is still emitted on its own line, so wrapping always terminates.

The scan walks whole code points, so an astral character (most emoji) is one glyph and a break never falls between the halves of a surrogate pair. Grapheme clusters are still not handled: a ZWJ sequence, a skin-tone modifier, or a flag is several code points and may wrap between them.

Parameters

content

string

The text to wrap.

width

number

The available width in display columns.

Returns

string[]

The wrapped lines — one or more per source paragraph, or an empty array when width is zero or less.

Example

ts
import { wrapText } from '@jsvision/ui';

wrapText('the quick brown fox', 10); // ['the quick', 'brown fox']
wrapText('one\n\ntwo', 10);          // ['one', '', 'two'] — the blank line survives

// Size a message box so nothing is clipped: frame (2) + button band (2) + the wrapped text.
const message = 'The file could not be opened.';
const width = 40;
const height = wrapText(message, width - 2).length + 4; // 5