# core/component/text (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/core/component/text/

Plain text renderer component.

## Text extends Component

Plain text renderer component.
- Component that draws 1 line of text in a single font / single size / single color.
- Bold / italic / underline / strikethrough apply to the whole text at once.
- Does not interpret markup tags (outputs them as is).
  Use the RichText component if rich text (markup + per-segment style) is needed.
- When disabled (isEnable() === false), skipped in draw / measurement.

Example: Load a font and write a single line

```js
import { Engine, EngineConfiguration, Scene, Vector2, WorldNode, Text, TextAlign, FontAsset } from "./build/vanilla.js";

class MainScene extends Scene {
	async load(engine) {
		await super.load(engine);
		const fontAsset = new FontAsset();
		await fontAsset.loadFont("DOSGothic", "examples/assets/DOSGothic.woff");
		const labelNode = new WorldNode();
		labelNode.setContentSize(Vector2.create(400, 60));
		labelNode.setLocalPosition(Vector2.create(320, 180));
		const text = labelNode.addComponent(Text);
		text.setFont(fontAsset);
		text.setFontSize(32);
		text.setTextColor("#ffffff");
		text.setStrokeColor("#000000");
		text.setStrokeWidth(4);
		text.setTextAlign(TextAlign.center);
		text.setText("Hello, Vanilla");
		const root = this.getRoot();
		root.addChild(labelNode);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor()` (constructor, since 0.2.1): Constructor.
- `tick(timeDelta)` (method, since 0.2.1): Update.
  - `timeDelta` number: Time since the last frame. (Seconds)
- `isTickNeeded()` (method, since 0.4.0): Whether tick has work to do. (false since it only draws, true if a subclass redefines tick)
  - returns boolean: True if tick has work to do.
- `draw(graphic)` (method, since 0.2.1): Draw. (skipped if disabled)
  - `graphic` Graphic: Graphics.
- `applyVisibleCharacterCount(text)` (method, since 0.3.0): Truncates from the start to the display character count. (in grapheme clusters, so final consonants, combining marks and emoji clusters are not split)
  - `text` string: Text to slice.
  - returns string: Text cut from the front to the visible character count. (the text as is if the visible character count is -1)
- `drawWrappedText(graphic, contentSize, fullText)` (method, since 0.3.0): Draws multi-line text. (automatic word wrap + explicit line breaks + display character count)
  - textBaseline is used as the vertical alignment of the line block. (top / middle / bottom)
  - `graphic` Graphic: Graphics.
  - `contentSize` Vector2: The node's content size.
  - `fullText` string: Whole text to draw. (before cutting to the visible character count)
- `readWrappedLines(text, wrapWidth)` (method, since 0.4.0): Returns the array of lines to draw. (remembers and reuses the result of wrapTextToLines)
  - Re-splits only when the text, font, size, bold, italic, width or wrap mode changes, or when a web font is downloaded or uploaded.
  - The returned array is held by this component until the next split, so do not modify it.
  - `text` string: Text to split.
  - `wrapWidth` number: Width at which lines wrap. (content size units)
  - returns string[]: Array of wrapped lines. (held by this component so do not modify)
- `wrapTextToLines(text, maxWidth)` (method, since 0.3.0): Splits text into an array of lines to fit the width.
  - "word": fills by space units, and force-splits by character when one word exceeds the width.
    (a CJK sentence without spaces is one whole word, so it naturally becomes character units)
  - "char": character units from the start.
  - Explicit line breaks (\n) are always kept.
  - `text` string: Text to split.
  - `maxWidth` number: Width at which lines wrap. (content size units, splits only at line breaks if 0 or less)
  - returns string[]: Array of wrapped lines. (split only at line breaks if there is no measuring canvas)
- `wrapLinesWithoutGraphic(maximumWidth)` (method, since 0.4.0): List of lines split without Graphic. (splits by the current text, font and width; null if there is no canvas to measure with)
  - Used by layouts that need the line count before drawing (such as placing window content). (same use as wrap_lines_without_graphic in the Rust version)
  - `maximumWidth` number: Width at which lines wrap. (content size units, splits only at line breaks if 0 or less)
  - returns string[] | null: Array of wrapped lines. (null if there is no measuring canvas)
- `measureWrappedSize()` (method, since 0.3.0): Measures the size with word wrap applied. (for layout)
  - returns object: { width, height, lineCount }
- `drawPlainText(graphic, contentSize, text)` (method, since 0.2.1): Draws plain text.
  - `graphic` Graphic: Graphics.
  - `contentSize` Vector2: The node's content size.
  - `text` string: Single line of text to draw. (already cut to the visible character count)
- `measurePlainTextWidth(text)` (method, since 0.2.1): Measures the pixel width of plain text. (uses an offscreen context)
  - `text` string: Text to measure.
  - returns number: Text width measured at the set size. (content size units)
- `measureText(text = this.#text, fontSize = this.#fontSize)` (method, since 0.4.0): Measures the width of text. (with this text's font, bold and italic; if not given, the current text and the set size)
  - Does not remeasure if the font string and text are the same. (measureTextMetrics cache, cleared when a web font is downloaded)
  - 0 if there is no document.
  - `text` string: Text to measure. (the current text if omitted)
  - `fontSize` number: Font size. (the set size if omitted)
  - returns number: Text width. (content size units, 0 if the text is empty or there is no document)
- `measureTextWithoutSpacing(text, fontSize)` (method, since 0.4.0): Text width without letter spacing added. (the base of measureText and drawTextLine)
  - `text` string: Text to measure.
  - `fontSize` number: Font size.
  - returns number: Width measured without letter spacing. (0 if there is no document)
- `drawTextLine(graphic, text, x, y, textAlign, fontSize, isStroke)` (method, since 0.4.0): Draws a single line of text. (in one go if the letter spacing is 0, otherwise at positions with the spacing added per grapheme cluster)
  - position(k) = position(k-1) + (width of the previous cluster and this cluster joined) - (width of this cluster alone) + letter spacing. Pair kerning is kept.
  - The total text width is the cluster count x letter spacing added to the width. (like CSS letter-spacing, it is also added after the last character) Alignment uses this width.
  - Right-to-left text is drawn without letter spacing.
  - `graphic` Graphic: Graphic. (with font, color, alignment and vertical baseline already set)
  - `text` string: Single line of text to draw.
  - `x` number: Alignment reference X.
  - `y` number: Vertical reference Y.
  - `textAlign` string: Actual horizontal alignment. ("left", "right", "center")
  - `fontSize` number: Font size. (for measuring positions)
  - `isStroke` boolean: Outline if true, fill if false.
- `setFitWidth(width, minimumRatio = 0.55)` (method, since 0.4.0): Sets fitting single-line text to a width. (if it overflows, draws it shrunk from the initial size down to the minimum ratio)
  - Used where the text overflows its box because text length differs per language and the box cannot be widened (buttons, row labels, titles).
  - Keeps the set size (getFontSize) and shrinks only the draw size (getFittedFontSize). Refits when the text or font changes.
  - If it still overflows after shrinking to the minimum ratio, draws it overflowing. Off-screen culling considers the overflowing width. (calculateDrawnRect)
  - Text that wraps (setWordWrapWidth, line break characters) is not fitted.
  - No fitting if width is 0 or less. (default)
  - `width` number: Width to fit. (content size units, negative becomes 0, no fitting if 0)
  - `minimumRatio` number: 0 ~ 1, default 0.55.

  Example: Shrink overflowing text to fit

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, WorldNode, Text } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const buttonNode = new WorldNode();
  		buttonNode.setContentSize(Vector2.create(160, 48));
  		buttonNode.setLocalPosition(Vector2.create(320, 180));
  		const text = buttonNode.addComponent(Text);
  		text.setFontSize(32);
  		text.setText("Start a new adventure");
  		text.setFitWidth(160, 0.5);
  		const fittedFontSize = text.getFittedFontSize();
  		console.log(fittedFontSize);
  		const root = this.getRoot();
  		root.addChild(buttonNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getFitWidth()` (method, since 0.4.0): Returns the width to fit. (no fitting if 0)
  - returns number: Width to fit. (no fitting if 0)
- `getFitMinimumRatio()` (method, since 0.4.0): Returns the minimum ratio to shrink to when fitting.
  - returns number: Smallest ratio to shrink to when fitting. (0 ~ 1)
- `getFittedFontSize()` (method, since 0.4.0): Returns the draw size. (the shrunk size if it exceeds the fit width, rounded down to 0.1 units; otherwise the set size)
  - returns number: Font size used when drawing.
- `calculateFittedFontSize()` (method, since 0.4.0): Measures and returns the draw size on the spot. (the shrunk size if it exceeds the fit width; same use as calculate_fitted_font_size in the Rust version)
  - This version can measure without Graphic, so it is the same value as getFittedFontSize. (remeasures if the text or font has changed)
  - returns number: Font size used when drawing.
- `writeGeometryKey(geometryKey)` (method, since 0.4.0): Writes the draw inputs to the geometry cache key. (text, font, size, colors, alignment, wrapping, visible character count, fit width, content size)
  - When a web font loads and text must be baked again, the text cache drops the entry, so Graphic notices and recomputes.
  - A subclass that overrides draw or the drawing functions under it (RichText etc.) returns false because what it reads is unknown. (that class overrides this function too to report them)
  - `geometryKey` GeometryKey: Key to write the inputs to.
  - returns boolean: True if the inputs were written.
- `calculateDrawnRect(rect)` (method, since 0.4.0): Writes the drawn rectangle to rect. (origin at the top-left of the node content area, used by off-screen culling, true if known)
  - Single-line text: adds the outline and half the font size on both sides of the aligned text width (fitted size, that width even when overflowing),
    and vertically allows a generous 1.5 times the font size above and below the baseline position.
  - Wrapping text: takes the widest of the split lines horizontally, and vertically adds a generous font size on each side of the line block (line count × line height).
  - If the text is empty nothing is drawn, so a size of 0 is written and true is returned. (draw draws nothing either, so a subtree holding an empty label can be skipped)
  - false if it cannot be measured. (not culled)
  - `rect` Rect: Where to write the drawn rectangle. (origin at the top-left of the node's content area)
  - returns boolean: True if written. (False if it cannot be measured)
- `calculateWrappedDrawnRect(rect, contentSize, text)` (method, since 0.4.0): Writes the drawn rectangle of wrapping text to rect. (called by calculateDrawnRect)
  - `rect` Rect: Rect to write the drawn area into.
  - `contentSize` Vector2: The node's content size.
  - `text` string: Text that wraps.
  - returns boolean: Always true.
- `getMeasuredLineCount()` (method, since 0.4.0): Number of lines from the last split. (only while the text, font and wrap width are unchanged since drawing; otherwise -1)
  - Lines are split when drawing. Used by layouts that read the drawn result and re-place. Multi-line text without a wrap width (setWordWrapWidth) splits by the node width, so it is -1.
  - 1 for single-line text.
  - returns number: Number of wrapped lines. (-1 if unknown)
- `computeUnderlineStartX(drawX, textWidth, textAlign = this.#textAlign)` (method, since 0.2.1): Calculates the underline start X coordinate. (corrects the cursor position of canvas fillText based on textAlign)
  - `drawX` number: X coordinate where the text was drawn. (the alignment anchor)
  - `textWidth` number: Text width.
  - `textAlign` string: Actual alignment. (defaults to this text's alignment; "start" is treated as left, "end" as right)
  - returns number: X coordinate where the underline starts.
- `computeUnderlineOffsetY(fontSize)` (method, since 0.2.1): Underline Y offset. (distance below the text from the baseline)
  - `fontSize` number: Font size.
  - returns number: Downward distance from the drawn Y to the underline. (depends on the vertical alignment)
- `computeStrikethroughOffsetY(fontSize)` (method, since 0.2.1): Strikethrough Y offset.
  - `fontSize` number: Font size.
  - returns number: Downward distance from the drawn Y to the strikethrough. (negative if above)
- `strokeHorizontalLine(graphic, x, y, width, lineWidth = 1)` (method, since 0.2.1): Horizontal line stroke.
  - `graphic` Graphic: Graphics.
  - `x` number: Start X coordinate.
  - `y` number: Y coordinate.
  - `width` number: Line length.
  - `lineWidth` number: Line width. (default 1)
- `getIntrinsicContentSize()` (method, since 0.2.1): Returns the natural size of the text. (same idea as UIKit's intrinsicContentSize)
  - Returns (-1, -1) when disabled (no effect on guides).
  - (-1, -1) if it cannot be measured (no document, etc.).
  - returns Vector2: Intrinsic size. (text width and font size, width 0 if the text is empty, (-1, -1) if it cannot be measured or is disabled)
- `setFont(font)` (method, since 0.2.1): Sets the font.
  - `font` FontFace | FontAsset: Font. (a FontFace or FontAsset, the system font if null or undefined, other types are ignored)
- `getFontFace()` (method, since 0.2.1): Returns the font.
  - returns FontFace: Font. (system font if null)
- `setWordWrapWidth(wordWrapWidth)` (method, since 0.3.0): Sets the automatic word wrap width. (single line if 0)
  - `wordWrapWidth` number: Automatic wrap width. (content size units, negative becomes 0, a single line if 0)

  Example: Wrap into multiple lines at a set width

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, WorldNode, Text, TextAlign, TextBaseline } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const messageNode = new WorldNode();
  		messageNode.setContentSize(Vector2.create(360, 200));
  		messageNode.setLocalPosition(Vector2.create(320, 180));
  		const text = messageNode.addComponent(Text);
  		text.setFontSize(24);
  		text.setTextAlign(TextAlign.left);
  		text.setTextBaseline(TextBaseline.top);
  		text.setWordWrapWidth(360);
  		text.setWrapMode("word");
  		text.setLineSpacing(1.4);
  		text.setText("The old bridge creaks under your feet.\nSomething moves in the water below.");
  		const root = this.getRoot();
  		root.addChild(messageNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getWordWrapWidth()` (method, since 0.3.0): Returns the automatic word wrap width.
  - returns number: Automatic wrap width. (a single line if 0)
- `setWrapMode(wrapMode)` (method, since 0.3.0): Sets the wrap mode. ("word" | "char")
  - `wrapMode` string: "word" wraps at spaces (an overflowing word wraps by character), "char" wraps by character.
- `getWrapMode()` (method, since 0.3.0): Returns the wrap mode.
  - returns string: Wrap mode. ("word" or "char")
- `setLineSpacing(lineSpacing)` (method, since 0.3.0): Sets the line spacing multiplier.
  - `lineSpacing` number: Line spacing scale. (multiplied by the font size, 0.1 if less than 0.1, initially 1.25)
- `getLineSpacing()` (method, since 0.3.0): Returns the line spacing multiplier.
  - returns number: Line spacing scale.
- `setLetterSpacing(letterSpacing)` (method, since 0.4.0): Sets the letter spacing. (same meaning as CSS letter-spacing and Unreal UMG letter spacing)
  - `letterSpacing` number: Spacing added after each grapheme cluster. (pixels, negative narrows, initially 0)
- `getLetterSpacing()` (method, since 0.4.0): Returns the letter spacing.
  - returns number: Letter spacing. (pixels, initially 0)
- `setVisibleCharacterCount(visibleCharacterCount)` (method, since 0.3.0): Sets the display character count. (-1 for all, for typewriter effects. In grapheme clusters)
  - `visibleCharacterCount` number: Visible character count. (in graphemes, floored, -1 if less than -1, everything if -1)

  Example: Reveal one character at a time

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, WorldNode, Text } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		const labelNode = new WorldNode();
  		labelNode.setContentSize(Vector2.create(480, 60));
  		labelNode.setLocalPosition(Vector2.create(320, 180));
  		this.text = labelNode.addComponent(Text);
  		this.text.setFontSize(28);
  		this.text.setText("Welcome to the village.");
  		this.text.setVisibleCharacterCount(0);
  		this.elapsedTime = 0;
  		const root = this.getRoot();
  		root.addChild(labelNode);
  	}
  
  	tick(timeDelta) {
  		super.tick(timeDelta);
  		this.elapsedTime += timeDelta;
  		const visibleCharacterCount = Math.floor(this.elapsedTime * 12);
  		this.text.setVisibleCharacterCount(visibleCharacterCount);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getVisibleCharacterCount()` (method, since 0.3.0): Returns the display character count.
  - returns number: Visible character count. (everything if -1)
- `setText(text)` (method, since 0.2.1): Sets the text. (does nothing if the text is the same)
  - `text` string: Text to show. (breaks lines at line break characters)
- `getText()` (method, since 0.2.1): Returns the text.
  - returns string: Text.
- `setFontSize(fontSize)` (method, since 0.2.1): Sets the text size.
  - `fontSize` number: Font size. (content size units, initially 32)
- `getFontSize()` (method, since 0.2.1): Returns the text size.
  - returns number: The set font size.
- `setTextColor(color)` (method, since 0.2.1): Sets the text color.
  - `color` Color | string | CanvasGradient | CanvasPattern: Text color. (a Color or a "#rrggbb(aa)" or "rgb(a)(...)" string, transparent if null or undefined, other values are ignored)
- `getTextColor()` (method, since 0.2.1): Returns the text color.
  - returns Color: Text color.
- `setStrokeColor(color)` (method, since 0.2.1): Sets the text outline color.
  - `color` Color | string | CanvasGradient | CanvasPattern: Stroke color. (a Color or a "#rrggbb(aa)" or "rgb(a)(...)" string, transparent if null or undefined, other values are ignored)
- `getStrokeColor()` (method, since 0.2.1): Returns the text outline color.
  - returns Color: Stroke color.
- `setStrokeWidth(width)` (method, since 0.2.1): Sets the text outline thickness.
  - `width` number: Stroke width. (content size units, no stroke if 0 or less)
- `getStrokeWidth()` (method, since 0.2.1): Returns the outline thickness.
  - returns number: Stroke width.
- `setBold(bold)` (method, since 0.2.1): Sets whether bold.
  - `bold` boolean: Whether bold. (bold only when true)
- `isBold()` (method, since 0.2.1): Returns whether bold.
  - returns boolean: True if bold.
- `setItalic(italic)` (method, since 0.2.1): Sets whether italic.
  - `italic` boolean: Whether italic. (italic only when true)
- `isItalic()` (method, since 0.2.1): Returns whether italic.
  - returns boolean: True if italic.
- `setUnderline(underline)` (method, since 0.2.1): Sets whether underlined.
  - `underline` boolean: Whether to underline. (only when true)
- `isUnderline()` (method, since 0.2.1): Returns whether underlined.
  - returns boolean: True if underlined.
- `setStrikethrough(strikethrough)` (method, since 0.2.1): Sets whether strikethrough.
  - `strikethrough` boolean: Whether to strike through. (only when true)
- `isStrikethrough()` (method, since 0.2.1): Returns whether strikethrough.
  - returns boolean: True if struck through.
- `setTextAlign(align)` (method, since 0.2.1): Sets the font horizontal alignment.
  - `align` "left" | "center" | "right" | "start" | "end": Horizontal alignment. ("start" and "end" follow the text direction, initially "center")
- `getTextAlign()` (method, since 0.2.1): Returns the font horizontal alignment.
  - returns string: Horizontal alignment. ("left", "center", "right", "start", "end")
- `setTextDirection(textDirection)` (method, since 0.3.2): Sets the text direction. ("inherit" | "ltr" | "rtl" | "auto", same as Graphic.setTextDirection)
  - "inherit" follows the Graphic direction at draw time. (default)
  - Alignment "start" / "end" becomes left or right according to this direction. (screens in right-to-left languages use "rtl" and "start")
  - `textDirection` "inherit" | "ltr" | "rtl" | "auto": Text direction. (initially "inherit")
- `getTextDirection()` (method, since 0.3.2): Returns the text direction.
  - returns string: Text direction. ("inherit", "ltr", "rtl", "auto")
- `setTextBaseline(baseline)` (method, since 0.2.1): Sets the font vertical alignment.
  - `baseline` "top" | "middle" | "bottom" | "alphabetic" | "hanging" | "ideographic": Vertical alignment. (for multi-line text, used as the vertical position of the line block, initially "middle")
- `getTextBaseline()` (method, since 0.2.1): Returns the font vertical alignment.
  - returns string: Vertical alignment.
- `static calculateTextBounds(graphic, textComponent)` (static, since 0.2.1): Returns the area where the text is drawn as a Rect. (for compatibility)
  - `graphic` Graphic: Graphics. (unused)
  - `textComponent` Text: Text component to measure.
  - returns Rect: Rect of the text width and actual height. (ignores bold and italic, an empty rect if it cannot be measured)

## Functions and constants

- `splitGraphemes(text)` (method, since 0.3.2): Splits into graphemes. (by code point if Intl.Segmenter is unavailable)
  - `text` string: Text to split.
  - returns string[]: List of graphemes.
- `splitWords(text)` (method, since 0.3.2): Splits into words. (the whole text as one piece if Intl.Segmenter is unavailable)
  - `text` string: Text to split.
  - returns string[]: One piece per word. (non-word pieces attach to the preceding word; words joined by non-breaking spaces are one piece)

  Example: Split into graphemes and words

  ```js
  import { splitGraphemes, splitWords, countGraphemes, sliceGraphemes } from "./build/vanilla.js";
  
  const text = "Cafe\u0301 au lait";
  const graphemes = splitGraphemes(text);
  console.log(graphemes.length, text.length);
  console.log(countGraphemes(text));
  console.log(sliceGraphemes(text, 4));
  console.log(splitWords("Hello, world. Bye"));
  ```

- `countGraphemes(text)` (method, since 0.4.0): Grapheme cluster count. (the unit the display character count counts; final consonants, combining marks and emoji clusters count as one character)
  - `text` string: Text to count.
  - returns number: Number of graphemes.
- `sliceGraphemes(text, count)` (method, since 0.4.0): Text up to the first count grapheme clusters. (the whole text if it is shorter)
  - `text` string: Text to slice.
  - `count` number: Number of graphemes to keep.
  - returns string: Text up to the first count graphemes. (the text as is if shorter)

## TextAlign (enum)

Sets the horizontal text alignment. (CanvasTextAlign)

- `left` = `left`: Left aligned. (placed at the left edge of the content)
- `center` = `center`: Center aligned. (placed at the horizontal center of the content)
- `right` = `right`: Right aligned. (placed at the right edge of the content)
- `start` = `start`: Aligned to the start side of the text direction. (left for "ltr", right for "rtl")
- `end` = `end`: Aligned to the end side of the text direction. (right for "ltr", left for "rtl")

## TextBaseline (enum)

Sets the vertical text alignment. (CanvasTextBaseline)

- `top` = `top`: Top of the text. (placed at the top edge of the content)
- `middle` = `middle`: Middle of the text. (placed at the vertical center of the content)
- `bottom` = `bottom`: Bottom of the text. (placed at the bottom edge of the content)
- `ideographic` = `ideographic`: Ideographic baseline. (placed at the bottom edge of the content)
- `hanging` = `hanging`: Hanging baseline. (placed at the top edge of the content)
- `alphabetic` = `alphabetic`: Alphabetic baseline. (placed at the bottom edge of the content)
