# core/component/text (vanilla-engine 0.4.0)

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

Text component. (draws text aligned within the node's content_size area)
- Draws a single line, or multiple lines if there are newline characters or a word_wrap_width.
- The split lines and line widths are recomputed only when the text, font string, wrap width or registered fonts change.
- Off-screen culling is judged by the text rectangle computed from alignment, overflow and wrapping results. (the original also culls with Text.calculateDrawnRect)
- Underline / strikethrough draw lines in the text color, as in the original. (thickness max(1, font size / 16), position from the original computeUnderlineOffsetY / computeStrikethroughOffsetY)
- Wrap mode (set_wrap_mode): Word fills by whitespace units, and if an overflowing piece holds several words (CJK, Thai and other scripts written without spaces) it breaks between words,
  and words that still overflow are split by grapheme clusters. Character uses grapheme clusters from the start. (the original "word" / "char", the calculation order matches the original)
  Grapheme clusters are found with UAX #29 (unicode-segmentation), words with the ICU dictionary (icu_segmenter). The original's Intl.Segmenter also uses the same ICU (ICU4C) rules and dictionary.
  For CJK, ICU4X picks the longest word first while ICU4C picks the split with the smallest sum of word costs, so they differ, and desktop ports ICU4C's calculation and splits with the same dictionary (cjdict).
- Italic adds italic to the font string. If there is no italic face, the text cache bakes it with a synthetic slant like the browser's (slope 1/4).
- Text direction (set_text_direction, the original setTextDirection): Inherit follows the Graphic's direction at draw time. Alignment Start / End resolves in that direction,
  and the text cache does bidirectional ordering and shaping (Arabic letter joining) in that paragraph direction.
- Showing a number of characters (set_visible_character_count, typewriter effect) cuts by grapheme clusters from the front. (Hangul syllables, combining marks and emoji sequences are not split)
  With multiple lines, each line draws as many as remain, and once the remaining count reaches 0 the following lines are not drawn.
- Fitting single-line text to a width (set_fit_width): as in the original, if it overflows it shrinks from the initial size down to the minimum ratio in steps of 0.1. The shrunk size is measured when splitting lines (update_layout), so
  a Graphic is needed to know it. (get_fitted_font_size is the last measured value, calculate_fitted_font_size measures on the spot) The drawn rectangle follows the width of the shrunk text.

Example: Count and cut by grapheme clusters

```rust
use vanilla::{count_graphemes, slice_graphemes, split_graphemes};

let text = "e\u{301}xy";
assert_eq!(text.chars().count(), 4);
assert_eq!(count_graphemes(text), 3);
assert_eq!(split_graphemes(text), vec!["e\u{301}", "x", "y"]);
assert_eq!(slice_graphemes(text, 2), "e\u{301}x");
assert_eq!(slice_graphemes(text, 9), text);
```

## TextWrappedSize (struct) (Clone, Copy, Debug, Default, PartialEq)

Size with wrapping applied. ({ width, height, lineCount } of the original measureWrappedSize)

Example: Size of text split by the wrap width

```rust
use vanilla::{Graphic, Text, TextWrappedSize};

fn measure_description(graphic: &mut Graphic) -> TextWrappedSize {
	let mut text = Text::create_with_text("A long description that wraps", 20.0);
	text.set_word_wrap_width(240.0);
	let wrapped_size = text.measure_wrapped_size(graphic);
	assert_eq!(wrapped_size.height, wrapped_size.line_count as f64 * 20.0 * text.get_line_spacing());
	wrapped_size
}
```

- `pub width: f64` (field, since 0.4.0): Width of the widest line. (pixels)
  - returns f64
- `pub height: f64` (field, since 0.4.0): Height. (line count * font size * line spacing)
  - returns f64
- `pub line_count: usize` (field, since 0.4.0): Line count. (0 if the text is empty)
  - returns usize

## Text (struct) (Default, Component, TypewriterTarget)

Text component. (the original Text, draws text aligned within the node's content_size area)

Example: Attach text to a node

```rust
use vanilla::{Colors, NodeTree, Text, TextAlign, Vector2};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let label_id = node_tree.create_child(root_id, "label");
node_tree[label_id].set_content_size(Vector2::create(300.0, 60.0));
let text = node_tree.add_component(label_id, Text::create_with_text("Hello", 24.0)).expect("text");
text.set_text_color(Colors::VANILLA);
text.set_text_align(TextAlign::Left);
text.set_stroke_width(2.0);
assert_eq!(text.get_text(), "Hello");
assert_eq!(text.build_font_string(), "24px default");
```

- `pub fn new() -> Text` (constructor, since 0.3.2): Constructor. (defaults are the same as the original: 32px, white, center alignment, middle baseline, line spacing 1.25)
  - returns Text: Text component with empty text. (font name default, Word wrapping, no outline)
- `pub fn create_with_text(text: &str, font_size: f64) -> Text` (static, since 0.3.2): Constructor with text and size.
  - `text` &str: Initial text.
  - `font_size` f64: Font size. (pixels)
  - returns Text: Component. (otherwise the same as new)
- `pub fn build_font_string(&self) -> String` (method, since 0.3.2): Builds a string in Canvas2D font form.
  - returns String: Font string. (e.g. `italic bold 32px default`, italic and bold are included only when on)
- `pub fn build_font_string_with_size(&self, font_size: f64) -> String` (method, since 0.4.0): Builds a string in Canvas2D font form with the given size. (with this text's font name, bold and italic)
  - `font_size` f64: Font size. (pixels)
  - returns String: Font string.

  Example: A string with bold, italic and the font name

  ```rust
  use vanilla::Text;
  
  let mut text = Text::new();
  text.set_bold(true);
  text.set_italic(true);
  text.set_font_family("GameFont");
  assert_eq!(text.build_font_string(), "italic bold 32px GameFont");
  assert_eq!(text.build_font_string_with_size(12.5), "italic bold 12.5px GameFont");
  ```

- `pub fn wrap_text_to_lines(&self, graphic: &Graphic, text: &str, maximum_width: f64) -> Vec<String>` (method, since 0.3.2): Splits lines to fit a width. (the original wrapTextToLines, newline characters are always kept, measured with the Graphic's current font string)
  - Word: fills by whitespace units. If an overflowing piece holds several words (text written without spaces), it splits between words and fills from the space left on the current line,
    and if a single word exceeds the width, it splits by grapheme clusters. (CJK sentences without spaces are also split between words)
  - Character: splits by grapheme clusters from the start.
  - `graphic` &Graphic: Graphic to measure with. (measures with the current font string)
  - `text` &str: Text to split.
  - `maximum_width` f64: Maximum line width. (pixels, if 0 or less, splits only at newline characters)
  - returns Vec<String>: List of lines. (an empty paragraph is an empty line)

  Example: Split lines with this text's font

  ```rust
  use vanilla::{Graphic, Text};
  
  fn wrap_description(graphic: &mut Graphic, text: &Text) -> Vec<String> {
  	graphic.set_font_string(&text.build_font_string());
  	text.wrap_text_to_lines(graphic, text.get_text(), 200.0)
  }
  ```

- `pub fn wrap_text_to_lines_with(&self, text: &str, maximum_width: f64, measure_width: &dyn Fn(&str) -> f64) -> Vec<String>` (method, since 0.4.0): Splits lines to fit a width. (takes a measuring function. The calculation of wrap_text_to_lines, for testing without a Graphic or measuring with another font)
  - `text` &str: Text to split.
  - `maximum_width` f64: Maximum line width. (same unit as measure_width, if 0 or less, splits only at newline characters)
  - `measure_width` &dyn Fn(&str) -> f64: Function that takes text and returns its width.
  - returns Vec<String>: List of lines. (an empty paragraph is an empty line)

  Example: Split by measuring each character as width 10

  ```rust
  use vanilla::{Text, TextWrapMode};
  
  let measure_width = |line_text: &str| -> f64 {
  	line_text.chars().count() as f64 * 10.0
  };
  let mut text = Text::new();
  assert_eq!(text.wrap_text_to_lines_with("aaa bbb ccc", 75.0, &measure_width), vec!["aaa bbb", "ccc"]);
  assert_eq!(text.wrap_text_to_lines_with("a\n\nb", 0.0, &measure_width), vec!["a", "", "b"]);
  text.set_wrap_mode(TextWrapMode::Character);
  assert_eq!(text.wrap_text_to_lines_with("abcdef", 25.0, &measure_width), vec!["ab", "cd", "ef"]);
  ```

- `pub fn wrap_lines_without_graphic(&self, maximum_width: f64) -> Option<Vec<String>>` (method, since 0.4.0): List of lines split without a Graphic. (split by the current text, font string and width, None if it cannot measure because there is no font)
  - Used by layouts that need the line count before drawing (such as placing window contents). (textstringtexturecache::measure_text_without_graphic)
  - `maximum_width` f64: Maximum line width. (pixels, if 0 or less, splits only at newline characters)
  - returns Option<Vec<String>>: List of lines. None on desktop if there is no text cache with fonts registered on this thread or no face to choose.

  Example: Split lines without a Graphic after registering a font

  ```rust
  use vanilla::core::textstringtexturecache::TextStringTextureCache;
  use vanilla::platform::find_fallback_font_file;
  use vanilla::Text;
  
  let text = Text::create_with_text("one two three four five", 20.0);
  assert!(text.wrap_lines_without_graphic(100.0).is_none());
  if let Some(source) = find_fallback_font_file("A", 400, false, false) {
  	let mut text_string_texture_cache = TextStringTextureCache::new();
  	text_string_texture_cache.set_default_font(false, std::fs::read(&source.path).expect("font file")).expect("font");
  	let line_list = text.wrap_lines_without_graphic(100.0).expect("lines");
  	assert!(line_list.len() > 1);
  }
  ```

- `pub fn measure_wrapped_size(&self, graphic: &mut Graphic) -> TextWrappedSize` (method, since 0.4.0): Measures the size with wrapping applied. (the original measureWrappedSize, for layout. Without a wrap width it splits only at newline characters)
  - `graphic` &mut Graphic: Graphic to measure with. (its state is restored)
  - returns TextWrappedSize: Size. (all 0 if the text is empty)
- `pub fn calculate_intrinsic_content_size(&self, graphic: &Graphic) -> Vector2` (method, since 0.4.0): Intrinsic size of the text. (the original getIntrinsicContentSize: single-line width and font size, (0, font size) if there is no text, (-1, -1) if disabled)
  - `graphic` &Graphic: Graphic to measure with.
  - returns Vector2: (width, font size). (pixels)
- `pub fn calculate_text_bounds(graphic: &Graphic, text_component: &Text) -> Rect` (static, since 0.4.0): Area occupied by the text. (the original Text.calculateTextBounds: the width measured without bold or italic, and the actual glyph height from top to bottom)
  - `graphic` &Graphic: Graphic to measure with.
  - `text_component` &Text: Component to measure. (uses the font name, font size and text)
  - returns Rect: The (0, 0, width, top to bottom height) rectangle. (pixels)
- `pub fn set_fit_width(&mut self, width: f64, minimum_ratio: f64)` (method, since 0.4.0): Sets fitting single-line text to a width. (if it overflows, shrinks from the initial size down to the minimum ratio, the original setFitWidth)
  - Used where the box cannot be widened (buttons, row names, titles) and text whose length differs by language overflows.
  - The set size (get_font_size) stays as is, only the size at draw time shrinks. If it still overflows at the minimum ratio it draws overflowing, and off-screen culling also considers the overflowing width.
  - Wrapping text is not fitted. Not fitted if width is 0 or less. (default) minimum_ratio is 0 ~ 1 (the original default 0.55)
  - `width` f64: Width to fit. (pixels, 0 if negative)
  - `minimum_ratio` f64: Smallest ratio to shrink to. (clamped to 0 ~ 1)

  Example: Fit a button label to 200 pixels

  ```rust
  use vanilla::{Graphic, Text};
  
  fn fit_button_label(graphic: &mut Graphic) {
  	let mut text = Text::create_with_text("Start a new adventure", 32.0);
  	text.set_fit_width(200.0, 0.55);
  	let fitted_font_size = text.calculate_fitted_font_size(graphic);
  	assert!(fitted_font_size <= 32.0);
  	assert_eq!(text.get_font_size(), 32.0);
  }
  ```

- `pub fn get_fit_width(&self) -> f64` (method, since 0.4.0): Returns the width to fit. (no fitting if 0)
  - returns f64: Width to fit. (pixels)
- `pub fn get_fit_minimum_ratio(&self) -> f64` (method, since 0.4.0): Returns the minimum ratio to shrink to when fitting.
  - returns f64: Ratio. (0 ~ 1, default 0.55)
- `pub fn get_fitted_font_size(&self) -> f64` (method, since 0.4.0): Returns the size at draw time. (the value from the last draw or measure, the shrunk size if it was fitted)
  - returns f64: Size. (pixels, the set size if lines still need to be recomputed)
- `pub fn get_measured_line_count(&self) -> Option<usize>` (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 None)
  - Lines are split at draw time with the Graphic's font. Used by layouts without a Graphic (such as placing window contents) to read the drawn result and place again.
  - Multi-line text without a wrap width (set_word_wrap_width) is split by the node width, so it is None.
  - returns Option<usize>: Line count. None if not split yet, changed since, or split by the node width.
- `pub fn set_font_family(&mut self, font_family: &str)` (method, since 0.3.2): Sets the font name. (a name registered in the Graphic, the default font if missing)
  - `font_family` &str: Font name.
- `pub fn get_font_family(&self) -> &str` (method, since 0.3.2): Returns the font name.
  - returns &str: Font name. (default is default)
- `pub fn set_word_wrap_width(&mut self, word_wrap_width: f64)` (method, since 0.3.2): Sets the wrap width. (if 0, splits only at newline characters)
  - `word_wrap_width` f64: Wrap width. (pixels, if 0 or less, splits only at newline characters)
- `pub fn get_word_wrap_width(&self) -> f64` (method, since 0.3.2): Returns the wrap width.
  - returns f64: Wrap width. (pixels)
- `pub fn calculate_fitted_font_size(&mut self, graphic: &mut Graphic) -> f64` (method, since 0.4.0): Measures and returns the size at draw time on the spot. (the shrunk size if it exceeds the fit width)
  - `graphic` &mut Graphic: Graphic to measure with.
  - returns f64: Size. (pixels)
- `pub fn measure_text(&self, graphic: &Graphic, text: &str, font_size: f64) -> f64` (method, since 0.4.0): Measures the text width. (with this text's font name, bold, italic and the given size, the original measureText)
  - The text cache does not measure again if the font string and text are the same. (TextStringTextureCache.measure_text)
  - `graphic` &Graphic: Graphic to measure with.
  - `text` &str: Text to measure.
  - `font_size` f64: Size to measure at. (pixels)
  - returns f64: Width. (pixels, 0 for empty text)
- `pub fn set_wrap_mode(&mut self, wrap_mode: TextWrapMode)` (method, since 0.4.0): Sets the wrap mode. (default Word)
  - `wrap_mode` TextWrapMode: Wrap mode.
- `pub fn get_wrap_mode(&self) -> TextWrapMode` (method, since 0.4.0): Returns the wrap mode.
  - returns TextWrapMode: Wrap mode.
- `pub fn set_line_spacing(&mut self, line_spacing: f64)` (method, since 0.3.2): Sets the line spacing. (multiple of the font size)
  - `line_spacing` f64: Line spacing. (multiple of the font size, default 1.25)
- `pub fn get_line_spacing(&self) -> f64` (method, since 0.3.2): Returns the line spacing.
  - returns f64: Line spacing. (multiple of the font size)
- `pub fn set_letter_spacing(&mut self, letter_spacing: f64)` (method, since 0.4.0): Sets the letter spacing. (same meaning as CSS letter-spacing and Unreal UMG letter spacing. original setLetterSpacing)
  - `letter_spacing` f64: Spacing added after each grapheme cluster. (pixels, negative narrows, default 0)

  Example: Setting the letter spacing

  ```rust
  use vanilla::Text;
  
  let mut text = Text::new();
  assert_eq!(text.get_letter_spacing(), 0.0);
  text.set_letter_spacing(2.5);
  assert_eq!(text.get_letter_spacing(), 2.5);
  ```

- `pub fn get_letter_spacing(&self) -> f64` (method, since 0.4.0): Returns the letter spacing.
  - returns f64: Letter spacing. (pixels, default 0)
- `pub fn set_visible_character_count(&mut self, visible_character_count: i32)` (method, since 0.3.2): Sets the visible character count. (-1 for all, for typewriter effects. Values below -1 are set to -1)
  - `visible_character_count` i32: Number of visible character clusters. (-1 for all)
- `pub fn get_visible_character_count(&self) -> i32` (method, since 0.3.2): Returns the visible character count.
  - returns i32: Number of visible character clusters. (-1 for all)
- `pub fn set_text(&mut self, text: &str)` (method, since 0.3.2): Sets the text.
  - `text` &str: Text. (multiple lines with newline characters)
- `pub fn get_text(&self) -> &str` (method, since 0.3.2): Returns the text.
  - returns &str: Text.
- `pub fn set_font_size(&mut self, font_size: f64)` (method, since 0.3.2): Sets the font size. (pixels)
  - `font_size` f64: Font size. (pixels, default 32)
- `pub fn get_font_size(&self) -> f64` (method, since 0.3.2): Returns the font size.
  - returns f64: Font size. (pixels, the set size, not the size shrunk to fit)
- `pub fn set_text_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the text color.
  - `color` impl Into<Color>: Text color. (default white)
- `pub fn get_text_color(&self) -> Color` (method, since 0.3.2): Returns the text color.
  - returns Color: Text color.
- `pub fn set_stroke_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the outline color.
  - `color` impl Into<Color>: Outline color. (default white)
- `pub fn get_stroke_color(&self) -> Color` (method, since 0.3.2): Returns the outline color.
  - returns Color: Stroke color.
- `pub fn set_stroke_width(&mut self, stroke_width: f64)` (method, since 0.3.2): Sets the outline thickness. (no outline if 0)
  - `stroke_width` f64: Outline thickness. (pixels, default 0)
- `pub fn get_stroke_width(&self) -> f64` (method, since 0.3.2): Returns the outline thickness.
  - returns f64: Outline thickness. (pixels)
- `pub fn set_bold(&mut self, is_bold: bool)` (method, since 0.3.2): Sets bold.
  - `is_bold` bool: If true, bold.
- `pub fn is_bold(&self) -> bool` (method, since 0.3.2): Whether bold.
  - returns bool: true if bold.
- `pub fn set_italic(&mut self, is_italic: bool)` (method, since 0.3.2): Sets italic. (adds italic to the font string)
  - `is_italic` bool: If true, italic.
- `pub fn is_italic(&self) -> bool` (method, since 0.3.2): Whether italic.
  - returns bool: true if italic.
- `pub fn set_underline(&mut self, is_underline: bool)` (method, since 0.4.0): Sets underline.
  - `is_underline` bool: If true, draws an underline.
- `pub fn is_underline(&self) -> bool` (method, since 0.4.0): Whether underlined.
  - returns bool: true if an underline is drawn.
- `pub fn set_strikethrough(&mut self, is_strikethrough: bool)` (method, since 0.4.0): Sets strikethrough.
  - `is_strikethrough` bool: If true, draws a strikethrough.
- `pub fn is_strikethrough(&self) -> bool` (method, since 0.4.0): Whether strikethrough.
  - returns bool: true if a strikethrough is drawn.
- `pub fn set_text_align(&mut self, text_align: TextAlign)` (method, since 0.3.2): Sets the horizontal alignment.
  - `text_align` TextAlign: Horizontal alignment. (default Center)
- `pub fn get_text_align(&self) -> TextAlign` (method, since 0.3.2): Returns the horizontal alignment.
  - returns TextAlign: Horizontal alignment.
- `pub fn set_text_direction(&mut self, text_direction: TextDirection)` (method, since 0.4.0): Sets the text direction. (Inherit | Ltr | Rtl | Auto, the original setTextDirection)
  - Inherit follows the Graphic's 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)
  - `text_direction` TextDirection: Text direction.
- `pub fn get_text_direction(&self) -> TextDirection` (method, since 0.4.0): Returns the text direction.
  - returns TextDirection: Text direction. (default Inherit)
- `pub fn set_text_baseline(&mut self, text_baseline: TextBaseline)` (method, since 0.3.2): Sets the vertical baseline.
  - `text_baseline` TextBaseline: Vertical baseline. (default Middle)
- `pub fn get_text_baseline(&self) -> TextBaseline` (method, since 0.3.2): Returns the vertical baseline.
  - returns TextBaseline: Vertical baseline.

## Functions and constants

- `pub fn split_graphemes(text: &str) -> Vec<&str>` (method, since 0.4.0): Splits into grapheme clusters. (the original splitGraphemes, UAX #29 extended grapheme clusters: Hangul final consonants, tone marks, combining marks and emoji sequences are not separated from the preceding character)
  - `text` &str: Text to split.
  - returns Vec<&str>: List of grapheme clusters. (slices borrowing text)
- `pub fn count_graphemes(text: &str) -> usize` (method, since 0.4.0): Number of grapheme clusters. (the unit counted by the visible character count)
  - `text` &str: Text to count.
  - returns usize: Number of graphemes.
- `pub fn slice_graphemes(text: &str, count: usize) -> &str` (method, since 0.4.0): Text up to the first count grapheme clusters. (the original sliceGraphemes, the whole text if it is shorter)
  - `text` &str: Text.
  - `count` usize: Number of graphemes to keep.
  - returns &str: Front slice. (borrows text)
- `pub fn find_grapheme_prefix_length(text: &str, count: usize) -> usize` (method, since 0.4.0): Byte length up to the first count grapheme clusters. (the whole text length if it is shorter)
  - `text` &str: Text.
  - `count` usize: Number of graphemes.
  - returns usize: Byte length.
- `pub fn split_words(text: &str) -> Vec<String>` (method, since 0.4.0): Splits into words. (the original splitWords, for wrapping)
  - Also finds word boundaries in scripts written without spaces, such as Thai, Lao, Khmer, Burmese and CJK. (ICU4X dictionary word segmentation, CJK runs are split again with the same calculation as Chrome's ICU4C CjkBreakEngine)
    Like the browser (ICU4C), a run of consecutive Hangul is treated as a separate word. (Rust followed by a Hangul particle splits into "Rust" and the particle. ICU4X joins Hangul and Latin letters into one word)
    On the web, as in the original, it splits with the browser's Intl.Segmenter. (in browsers without it, the whole text is one piece as in the original)
  - Non-word pieces such as punctuation are attached to the preceding word. (so punctuation does not start a line) A leading one is attached before the first word.
  - Words joined by a no-break space (U+00A0) are not split. (things that must stay together, such as a name and value, or a number and unit)
  - `text` &str: Text to split.
  - returns Vec<String>: List of word pieces. (joining the pieces gives the original text)

  Example: Punctuation goes to the preceding word, a no-break space joins

  ```rust
  use vanilla::split_words;
  
  assert_eq!(split_words("Hello, world!"), vec!["Hello, ", "world!"]);
  assert_eq!(split_words("HP\u{00A0}100 MP"), vec!["HP\u{00A0}100 ", "MP"]);
  ```

- `pub fn segment_words(text: &str) -> Vec<(&str, bool)>` (method, since 0.4.0): Splits into word pieces. (a list of (piece, whether it is a word), Hangul run boundaries added to the ICU word boundaries)
  - `text` &str: Text to split.
  - returns Vec<(&str, bool)>: List of (piece, whether it is a word). (joining the pieces gives the original text)

## TextWrapMode (enum) (Clone, Copy, Debug, PartialEq, Eq)

Wrap mode. (the original wrapMode "word" / "char")

- `Word`: Fills by whitespace units, and if a single word exceeds the width, splits by characters. (a CJK sentence without spaces is one whole word, so it becomes character units)
- `Character`: Splits by characters from the start.
