# ui/uilabel (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/ui/uilabel/

UI label.

## UILabel extends UIView

UI label.
- Display only. Inherits UIView since it takes no input.
- When attached to a node, attaches both the Text and RichText components internally.
  (RichText inherits Text, so the component add order is fixed as Text → RichText)
- The default mode is plain text. Calling useRichText(true) enables RichText so that
  markup such as <b> / <i> / <u> / <s> / <color=...> / <size=N> is interpreted.
- All text / font / style setters are synced to both Text / RichText.
  (so the text is kept when the mode toggles)
- On setText, calls the host node's invalidateIntrinsicContentSize automatically.

Example: Multi-line label with an outline

```js
import { Engine, EngineConfiguration, UIScene, UILabel, WorldNode, Pivot, Vector2, Color } from "./build/vanilla.js";

class MainScene extends UIScene {
	constructor() {
		super();
		this.setLoadingMinDurationMs(0);
	}

	initialize(engine) {
		super.initialize(engine);
		const labelNode = new WorldNode();
		labelNode.setPivot(Pivot.topLeft);
		labelNode.setAnchor(Pivot.topLeft);
		labelNode.setLocalPosition(Vector2.create(40, 40));
		labelNode.setContentSize(Vector2.create(280, 120));
		const label = labelNode.addComponent(UILabel);
		label.setFontSize(22);
		label.setTextColor(new Color(1, 0.95, 0.8, 1));
		label.setStrokeColor(new Color(0.1, 0.1, 0.15, 1));
		label.setStrokeWidth(3);
		label.setTextAlign("left");
		label.setWordWrapWidth(280);
		label.setLineSpacing(1.4);
		label.setText("A long line of text wraps inside the label width.");
		const root = this.getRoot();
		root.addChild(labelNode);
		console.log(label.getText(), label.measureText());
	}
}

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

- `constructor()` (constructor, since 0.2.1): Constructor.
- `require()` (method, since 0.2.1): Dependent components; Text must be attached first for RichText to be added as a separate instance.
  (RichText extends Text, so reversing the order catches only a single RichText)
  - returns Function[]: Components to attach first. ([Text, RichText])
- `attach(node)` (method, since 0.2.1): Attached to a node. (acquires Text / RichText component references + applies the active state)
  - `node` ComponentNode: Node to attach to.
- `detach(node)` (method, since 0.2.1): Detached from a node.
  - `node` ComponentNode: Node being detached from.
- `invalidateIntrinsicContentSize()` (method, since 0.2.1): Calls invalidateIntrinsicContentSize if the host node has it.
- `applyActiveComponent()` (method, since 0.2.1): Applies the active component. (toggles setEnable of Text / RichText according to the current mode)
- `useRichText(useRichText)` (method, since 0.2.1): Sets rich text mode. If true, the RichText component is enabled and interprets markup.
  - `useRichText` boolean: Rich text mode if true. (turned on only for true)

  Example: Style only part of the text with markup

  ```js
  import { Engine, EngineConfiguration, UIScene, UILabel, WorldNode, Pivot, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const labelNode = new WorldNode();
  		labelNode.setPivot(Pivot.topLeft);
  		labelNode.setAnchor(Pivot.topLeft);
  		labelNode.setLocalPosition(Vector2.create(40, 40));
  		labelNode.setContentSize(Vector2.create(320, 40));
  		const label = labelNode.addComponent(UILabel);
  		label.setFontSize(24);
  		label.useRichText(true);
  		label.setText("Gold <b>120</b> <color=yellow>+30</color> <size=16>bonus</size>");
  		const root = this.getRoot();
  		root.addChild(labelNode);
  		console.log(label.isUsingRichText(), label.getText());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isUsingRichText()` (method, since 0.2.1): Returns whether in rich text mode.
  - returns boolean: True in rich text mode.
- `setText(text)` (method, since 0.2.1): Sets the text. Synced to both Text and RichText (preserved on mode toggle).
  - `text` string: Text to show. (read as markup in rich text mode)
- `getText()` (method, since 0.2.1): Returns the text. (plain text of the active component)
  - returns string: Text of the current mode. (empty before being attached to a node)
- `appendSegment(text, attributes)` (method, since 0.2.1): Adds 1 rich text segment. (applied directly to the RichText component)
  - useRichText(true) must be on for it to show on screen.
  - `text` string: Text to append.
  - `attributes` object: Format of that segment. ({ fontFace, fontSize, textColor, strokeColor, strokeWidth, bold, italic, underline, strikethrough }, colors are Color, missing ones use the label's values)
  - returns UILabel: This label. (calls can be chained)

  Example: Append segments with different formats

  ```js
  import { Engine, EngineConfiguration, UIScene, UILabel, WorldNode, Pivot, Vector2, Color } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const labelNode = new WorldNode();
  		labelNode.setPivot(Pivot.topLeft);
  		labelNode.setAnchor(Pivot.topLeft);
  		labelNode.setLocalPosition(Vector2.create(40, 40));
  		labelNode.setContentSize(Vector2.create(320, 40));
  		const label = labelNode.addComponent(UILabel);
  		label.setFontSize(22);
  		label.useRichText(true);
  		label.clearSegments();
  		label.appendSegment("HP ", { bold: true });
  		label.appendSegment("80", { textColor: new Color(1, 0.3, 0.3, 1), fontSize: 28 });
  		label.appendSegment(" / 100");
  		const root = this.getRoot();
  		root.addChild(labelNode);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `clearSegments()` (method, since 0.2.1): Removes all rich text segments.
- `setFontSize(fontSize)` (method, since 0.2.1): Sets the font size.
  - `fontSize` number: Font size. (content size units, initially 32)
- `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, Text.setFitWidth)
  - Rich text mode is not fitted. No fitting if width is 0 or less.
  - `width` number: Width to fit. (content size units, no fitting if 0 or less)
  - `minimumRatio` number: 0 ~ 1, default 0.55.

  Example: Shrink long text to fit the box width

  ```js
  import { Engine, EngineConfiguration, UIScene, UILabel, WorldNode, Pivot, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const labelNode = new WorldNode();
  		labelNode.setPivot(Pivot.topLeft);
  		labelNode.setAnchor(Pivot.topLeft);
  		labelNode.setLocalPosition(Vector2.create(40, 40));
  		labelNode.setContentSize(Vector2.create(160, 40));
  		const label = labelNode.addComponent(UILabel);
  		label.setFontSize(24);
  		label.setText("Continue the adventure");
  		label.setFitWidth(160, 0.5);
  		const root = this.getRoot();
  		root.addChild(labelNode);
  		console.log(label.getFontSize(), label.calculateFittedFontSize());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  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. (0 means no fitting, 0 before being attached to a node)
- `getFittedFontSize()` (method, since 0.4.0): Returns the draw size. (the shrunk size if shrunk to fit)
  - returns number: Font size when drawn. (0 before being attached to a node)
- `calculateFittedFontSize()` (method, since 0.4.0): Measures and returns the draw size on the spot. (Text.calculateFittedFontSize)
  - returns number: Font size when drawn, measured now. (0 before being attached to a node)
- `measureText(text = this.getText(), fontSize = this.getFontSize())` (method, since 0.4.0): Measures the width of text. (with this label's font, bold and italic; if not given, the current text and the set size, Text.measureText)
  - `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, before being attached to a node or if there is no document)
- `isDrawnInsideContent()` (method, since 0.4.0): Whether it draws only inside the content area. (the label itself only fills the background in the content area; the text is reported separately by Text)
  - returns boolean: Always true.
- `getFontSize()` (method, since 0.2.1): Returns the font size.
  - returns number: The set font size. (0 before being attached to a node)
- `setWordWrapWidth(wordWrapWidth)` (method, since 0.3.0): Sets the automatic word wrap width. (plain text mode only, single line if 0)
  - `wordWrapWidth` number: Automatic wrap width. (content size units, negative becomes 0, a single line if 0)
- `setWrapMode(wrapMode)` (method, since 0.3.0): Sets the wrap mode. ("word" | "char")
  - `wrapMode` string: word wraps at spaces (overflowing words by character), char wraps by character.
- `getWrapMode()` (method, since 0.4.0): Returns the wrap mode. ("word" | "char", "word" if there is no text)
  - 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)
- `setLetterSpacing(letterSpacing)` (method, since 0.4.0): Sets the letter spacing. (delegated to Text)
  - `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, plain text mode only. In grapheme clusters)
  - `visibleCharacterCount` number: Visible character count. (in grapheme clusters, floored, -1 means all)

  Example: Reveal one character at a time like a typewriter

  ```js
  import { Engine, EngineConfiguration, UIScene, UILabel, WorldNode, Pivot, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends UIScene {
  	constructor() {
  		super();
  		this.setLoadingMinDurationMs(0);
  		this.label = null;
  		this.elapsedSeconds = 0;
  	}
  
  	initialize(engine) {
  		super.initialize(engine);
  		const labelNode = new WorldNode();
  		labelNode.setPivot(Pivot.topLeft);
  		labelNode.setAnchor(Pivot.topLeft);
  		labelNode.setLocalPosition(Vector2.create(40, 40));
  		labelNode.setContentSize(Vector2.create(400, 40));
  		const label = labelNode.addComponent(UILabel);
  		label.setFontSize(22);
  		label.setTextAlign("left");
  		label.setText("Welcome to the village.");
  		label.setVisibleCharacterCount(0);
  		this.label = label;
  		const root = this.getRoot();
  		root.addChild(labelNode);
  	}
  
  	tick(timeDelta) {
  		super.tick(timeDelta);
  		if (this.label !== null) {
  			this.elapsedSeconds += timeDelta;
  			const characterCount = Math.floor(this.elapsedSeconds * 20);
  			this.label.setVisibleCharacterCount(characterCount);
  		}
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.canvasId = "mainCanvas";
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  engineConfiguration.autoResizeOnWindowResize = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getVisibleCharacterCount()` (method, since 0.4.0): Returns the display character count. (-1 for all, -1 if not yet attached)
  - returns number: Visible character count. (everything if -1)
- `setFont(font)` (method, since 0.2.1): Sets the font.
  - `font` FontFace | FontAsset | null: Font. (for a FontAsset its fontFace, the system font if null, other types are ignored)
- `setTextColor(color)` (method, since 0.2.1): Sets the text color.
  - `color` Color | string: Text color. (a Color or a "#rrggbb(aa)", "rgb(a)(...)" string, transparent if null or undefined, initially white)
- `getTextColor()` (method, since 0.2.1): Returns the text color.
  - returns Color | null: Text color. (null before being attached to a node)
- `setStrokeColor(color)` (method, since 0.2.1): Sets the text outline color.
  - `color` Color | string: Outline color. (a Color or a "#rrggbb(aa)", "rgb(a)(...)" string, transparent if null or undefined)
- `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)
- `setBold(bold)` (method, since 0.2.1): Sets bold.
  - `bold` boolean: Whether bold. (bold only when true)
- `isBold()` (method, since 0.2.1): Returns bold.
  - returns boolean: True if bold.
- `setItalic(italic)` (method, since 0.2.1): Sets italic.
  - `italic` boolean: Whether italic. (italic only when true)
- `isItalic()` (method, since 0.2.1): Returns italic.
  - returns boolean: True if italic.
- `setUnderline(underline)` (method, since 0.2.1): Sets underline.
  - `underline` boolean: Whether to underline. (only when true)
- `isUnderline()` (method, since 0.2.1): Returns underline.
  - returns boolean: True if underlined.
- `setStrikethrough(strikethrough)` (method, since 0.2.1): Sets strikethrough.
  - `strikethrough` boolean: Whether to strike through. (only when true)
- `isStrikethrough()` (method, since 0.2.1): Returns strikethrough.
  - returns boolean: True if struck through.
- `setTextAlign(align)` (method, since 0.2.1): Sets the horizontal alignment.
  - `align` "left" | "center" | "right" | "start" | "end": Horizontal alignment. ("start" and "end" follow the text direction, initially "center")
- `setTextDirection(textDirection)` (method, since 0.3.2): Sets the text direction. ("inherit" | "ltr" | "rtl" | "auto", same as Text.setTextDirection)
  - Rich text drawn with format pieces (segment) is joined left to right regardless of direction.
  - `textDirection` "inherit" | "ltr" | "rtl" | "auto": Text direction. (initially "inherit")
- `getTextDirection()` (method, since 0.3.2): Returns the text direction.
  - returns string: Text direction. ("inherit" before being attached to a node)
- `setTextBaseline(baseline)` (method, since 0.2.1): Sets the 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")
- `getTextAlign()` (method, since 0.3.0): Returns the horizontal alignment.
  - returns string: Horizontal alignment. ("center" before being attached to a node)
- `getTextBaseline()` (method, since 0.3.0): Returns the vertical alignment.
  - returns string: Vertical alignment. ("middle" before being attached to a node)
