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

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

Rich text component. (RichText and parse_markup_to_segments in the original core/component/richtext.js)
- Parses markup (the same form as Unity TMP) and joins segments into one line, each with its own font, size, color, bold, italic, underline and strikethrough.
  Supported tags: `<b>`, `<i>`, `<u>`, `<s>`, `<color=#RRGGBB[AA]>`, `<color=name>`, `<size=N>`. Unknown tags show up as plain text.
- The original inherits Text. The Rust version contains a Text (the same shape as UILabel containing a Text) and forwards the setters.
  Without markup it draws with the contained Text's draw. (multiple lines and wrap width as is) Properties a segment does not set use the Text's values.
- Segment layout (layout_segments) takes a measuring function instead of a Graphic. draw measures with measure_text of the text texture cache (textstringtexturecache).
- Differences from the original:
  - The segment property fontFace (FontFace / FontAsset) is font_family (a registered font name).
  - As in the original, a segment's underline, strikethrough and italic use the Text's values (set_underline, set_strikethrough, set_italic) when the segment property is absent.
  - An invalid #color (non-hexadecimal characters) is white. (the original gives a NaN color)
  - getIntrinsicContentSize is calculate_intrinsic_content_size, which takes a measuring function.
- Text direction: the paragraph direction is decided from the joined segment text (the contained Text's direction, the Graphic's direction if Inherit), and right to left places segments from the right.
  Each segment is shaped in that direction, and alignment Start / End is resolved in that direction too. (the original is the same)

## RichTextAttributes (struct) (Clone, Debug, Default, PartialEq)

Segment properties. (None / false uses the Text's value)

Example: Build segments in code

```rust
use vanilla::{Color, RichText, RichTextAttributes};

let mut warning_attributes = RichTextAttributes::new();
warning_attributes.text_color = Some(Color::create_from_hex("#ff0000"));
warning_attributes.font_size = Some(28.0);
warning_attributes.is_bold = true;
let mut rich_text = RichText::new();
rich_text.append_segment("HP ", RichTextAttributes::new()).append_segment("5", warning_attributes);
assert!(rich_text.has_segments());
assert_eq!(rich_text.get_segments()[0].attributes, RichTextAttributes::new());
assert_eq!(rich_text.get_segments()[1].attributes.font_size, Some(28.0));
```

- `pub text_color: Option<Color>` (field, since 0.3.2): Text color. (the Text's text color if None)
  - returns Option<Color>
- `pub font_size: Option<f64>` (field, since 0.3.2): Font size. (pixels, the Text's font size if None)
  - returns Option<f64>
- `pub font_family: Option<String>` (field, since 0.3.2): Font name. (the Text's font name if None)
  - returns Option<String>
- `pub stroke_color: Option<Color>` (field, since 0.3.2): Outline color. (the Text's outline color if None)
  - returns Option<Color>
- `pub stroke_width: Option<f64>` (field, since 0.3.2): Outline thickness. (pixels, the Text's outline thickness if None)
  - returns Option<f64>
- `pub is_bold: bool` (field, since 0.3.2): Bold. (false follows the Text's value)
  - returns bool
- `pub is_italic: bool` (field, since 0.3.2): Italic. (false follows the Text's value)
  - returns bool
- `pub is_underline: bool` (field, since 0.3.2): Underline. (false follows the Text's value)
  - returns bool
- `pub is_strikethrough: bool` (field, since 0.3.2): Strikethrough. (false follows the Text's value)
  - returns bool
- `pub fn new() -> RichTextAttributes` (constructor, since 0.3.2): Constructor. (nothing set)
  - returns RichTextAttributes: Properties with nothing set. (same as default)

## RichTextSegment (struct) (Clone, Debug, PartialEq)

Segment. (text + properties)

Example: Nested tags combine their properties

```rust
use vanilla::core::component::richtext::parse_markup_to_segments;
use vanilla::Color;

let segment_list = parse_markup_to_segments("A<b>B<color=red>C</color></b>").expect("segments");
assert_eq!(segment_list.len(), 3);
assert_eq!(segment_list[0].text, "A");
assert!(!segment_list[0].attributes.is_bold);
assert!(segment_list[2].attributes.is_bold);
assert_eq!(segment_list[2].attributes.text_color, Some(Color::create_from_hex("#ff0000")));
```

- `pub text: String` (field, since 0.3.2): Segment text. (text with the tags removed)
  - returns String
- `pub attributes: RichTextAttributes` (field, since 0.3.2): Segment properties. (nested tags combined)
  - returns RichTextAttributes

## RichTextRun (struct) (Clone, Debug, PartialEq)

One laid out segment. (the draw position and all properties resolved)

Example: Properties a segment does not set resolve to the Text's values

```rust
use vanilla::{Color, RichText, TextDirection, Vector2};

let mut measure_width = |_font_string: &str, text: &str| -> f64 {
	text.chars().count() as f64 * 10.0
};
let mut rich_text = RichText::create_with_text("ab<size=40><u>cd</u></size>", 20.0);
rich_text.set_text_color("#00ff00");
let layout = rich_text.layout_segments(Vector2::create(200.0, 60.0), TextDirection::Ltr, &mut measure_width);
let first_run = &layout.run_list[0];
let second_run = &layout.run_list[1];
assert_eq!(first_run.font_string, "20px default");
assert_eq!(first_run.text_color, Color::create_from_hex("#00ff00"));
assert!(!first_run.is_underline);
assert_eq!(second_run.font_size, 40.0);
assert!(second_run.is_underline);
assert_eq!(second_run.x, first_run.x + first_run.width);
```

- `pub text: String` (field, since 0.3.2): Segment text.
  - returns String
- `pub font_string: String` (field, since 0.3.2): Font string. (Canvas2D font form)
  - returns String
- `pub font_size: f64` (field, since 0.3.2): Font size. (pixels)
  - returns f64
- `pub x: f64` (field, since 0.3.2): Left x to draw at. (content coordinates, reflecting alignment and paragraph direction)
  - returns f64
- `pub width: f64` (field, since 0.3.2): Measured width.
  - returns f64
- `pub text_color: Color` (field, since 0.3.2): Text color.
  - returns Color
- `pub stroke_color: Color` (field, since 0.3.2): Stroke color.
  - returns Color
- `pub stroke_width: f64` (field, since 0.3.2): Outline thickness. (0 draws no outline)
  - returns f64
- `pub is_underline: bool` (field, since 0.3.2): Whether to draw an underline.
  - returns bool
- `pub is_strikethrough: bool` (field, since 0.3.2): Whether to draw a strikethrough.
  - returns bool

## RichTextLayout (struct) (Clone, Debug, PartialEq)

Segment layout result.

Example: Center alignment and middle baseline

```rust
use vanilla::{RichText, TextAlign, TextBaseline, TextDirection, Vector2};

let mut measure_width = |_font_string: &str, text: &str| -> f64 {
	text.chars().count() as f64 * 10.0
};
let mut rich_text = RichText::create_with_text("ab<size=40>cd</size>", 20.0);
rich_text.set_text_align(TextAlign::Center);
rich_text.set_text_baseline(TextBaseline::Middle);
let layout = rich_text.layout_segments(Vector2::create(200.0, 60.0), TextDirection::Ltr, &mut measure_width);
assert_eq!(layout.total_width, 40.0);
assert_eq!(layout.maximum_font_size, 40.0);
assert_eq!(layout.baseline_y, 30.0);
assert_eq!(layout.run_list[0].x, 80.0);
```

- `pub run_list: Vec<RichTextRun>` (field, since 0.3.2): List of laid out segments. (in segment order, excluding segments with empty text)
  - returns Vec<RichTextRun>
- `pub total_width: f64` (field, since 0.3.2): Sum of the segment widths.
  - returns f64
- `pub maximum_font_size: f64` (field, since 0.3.2): Largest font size. (pixels, 0 if there are no segments)
  - returns f64
- `pub baseline_y: f64` (field, since 0.3.2): Baseline y. (content coordinates, 0 for Top and Hanging, half the height for Middle, the height otherwise)
  - returns f64

## RichText (struct) (Default, Component)

Rich text component.
- As in the original, segments are joined into one line. Without markup it draws with the contained Text.

Example: Set markup text

```rust
use vanilla::RichText;

let mut rich_text = RichText::create_with_text("Get <b>100</b> <color=yellow>gold</color>", 20.0);
assert!(rich_text.has_segments());
assert_eq!(rich_text.get_segments().len(), 4);
assert_eq!(rich_text.get_text(), "Get <b>100</b> <color=yellow>gold</color>");
rich_text.set_text("plain text");
assert!(!rich_text.has_segments());
```

- `pub fn new() -> RichText` (constructor, since 0.3.2): Constructor. (defaults are the same as Text)
  - returns RichText: Rich text component with empty text.
- `pub fn create_with_text(text: &str, font_size: f64) -> RichText` (static, since 0.3.2): Constructor with text and size.
  - `text` &str: Initial text. (markup allowed)
  - `font_size` f64: Default font size. (pixels)
  - returns RichText: Component.
- `pub fn get_text_component(&self) -> &Text` (method, since 0.3.2): Returns the contained text component. (global properties and drawing when there is no markup)
  - returns &Text: The contained Text.
- `pub fn get_text_component_mut(&mut self) -> &mut Text` (method, since 0.3.2): Returns the contained text component. (mutable)
  - returns &mut Text: The contained Text.
- `pub fn set_text(&mut self, text: &str)` (method, since 0.3.2): Sets the text. (parses the markup into segments. If there are no known tags, clears the segments and draws as plain text)
  - `text` &str: Text. (markup allowed)
- `pub fn get_text(&self) -> &str` (method, since 0.3.2): Returns the text. (the original text containing the markup)
  - returns &str: Text.
- `pub fn append_segment(&mut self, text: &str, attributes: RichTextAttributes) -> &mut RichText` (method, since 0.3.2): Adds one segment. (for building segments in code without markup)
  - `text` &str: Segment text. (kept as is without parsing markup)
  - `attributes` RichTextAttributes: Segment properties.
  - returns &mut RichText: This component. (calls can be chained)
- `pub fn clear_segments(&mut self)` (method, since 0.3.2): Removes all segments.
- `pub fn get_segments(&self) -> &[RichTextSegment]` (method, since 0.3.2): List of segments.
  - returns &[RichTextSegment]: List of segments. (empty if there is no markup)
- `pub fn has_segments(&self) -> bool` (method, since 0.3.2): Whether there is at least one segment with text.
  - returns bool: true if there is a segment with text.
- `pub fn set_font_size(&mut self, font_size: f64)` (method, since 0.3.2): Sets the font size.
  - `font_size` f64: Default font size. (pixels, used by segments that do not set a size)
- `pub fn get_font_size(&self) -> f64` (method, since 0.3.2): Returns the font size.
  - returns f64: Default font size. (pixels)
- `pub fn set_font_family(&mut self, font_family: &str)` (method, since 0.3.2): Sets the font name.
  - `font_family` &str: Default font name.
- `pub fn get_font_family(&self) -> &str` (method, since 0.3.2): Returns the font name.
  - returns &str: Default font name.
- `pub fn set_text_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the text color.
  - `color` impl Into<Color>: Default text color.
- `pub fn get_text_color(&self) -> Color` (method, since 0.3.2): Returns the text color.
  - returns Color: Default 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>: Default outline color.
- `pub fn get_stroke_color(&self) -> Color` (method, since 0.3.2): Returns the outline color.
  - returns Color: Default outline color.
- `pub fn set_stroke_width(&mut self, stroke_width: f64)` (method, since 0.3.2): Sets the outline thickness.
  - `stroke_width` f64: Default outline thickness. (pixels, none if 0)
- `pub fn get_stroke_width(&self) -> f64` (method, since 0.3.2): Returns the outline thickness.
  - returns f64: Default outline thickness. (pixels)
- `pub fn set_bold(&mut self, is_bold: bool)` (method, since 0.3.2): Sets bold.
  - `is_bold` bool: If true, all segments are 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.
  - `is_italic` bool: If true, all segments are 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 the underline. (drawn on all segments even if a segment has no `<u>`)
  - `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 the strikethrough. (drawn on all segments even if a segment has no `<s>`)
  - `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_wrap_mode(&mut self, wrap_mode: TextWrapMode)` (method, since 0.4.0): Sets the wrap mode. (used only without markup. Segments are one line as in the original)
  - `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_text_align(&mut self, text_align: TextAlign)` (method, since 0.3.2): Sets the horizontal alignment.
  - `text_align` TextAlign: Horizontal alignment. (segments are aligned by their combined width)
- `pub fn get_text_align(&self) -> TextAlign` (method, since 0.3.2): Returns the horizontal alignment.
  - returns TextAlign: Horizontal alignment.
- `pub fn set_text_baseline(&mut self, text_baseline: TextBaseline)` (method, since 0.3.2): Sets the vertical baseline.
  - `text_baseline` TextBaseline: Vertical baseline.
- `pub fn get_text_baseline(&self) -> TextBaseline` (method, since 0.3.2): Returns the vertical baseline.
  - returns TextBaseline: Vertical baseline.
- `pub fn set_word_wrap_width(&mut self, word_wrap_width: f64)` (method, since 0.3.2): Sets the wrap width. (used only without markup. Segments are one line as in the original)
  - `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 set_line_spacing(&mut self, line_spacing: f64)` (method, since 0.3.2): Sets the line spacing.
  - `line_spacing` f64: Line spacing. (multiple of the font size, used only without markup)
- `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.
  - `letter_spacing` f64: Spacing added after each grapheme cluster. (pixels, used only when there is no markup)
- `pub fn get_letter_spacing(&self) -> f64` (method, since 0.4.0): Returns the letter spacing.
  - returns f64: Letter spacing. (pixels)
- `pub fn layout_segments(&self, content_size: Vector2, text_direction: TextDirection, measure_width: &mut dyn FnMut(&str, &str) -> f64) -> RichTextLayout` (method, since 0.3.2): Segment layout. (aligned using the combined width and the largest font size, baseline by the same rule as Text. The position calculation of the original drawSegments)
  - measure_width(font string, text) returns the text width.
  - text_direction is the actual paragraph direction. (Ltr or Rtl, Rtl places segments from the right and Start aligns right)
  - `content_size` Vector2: Node content size. (used for alignment and baseline)
  - `text_direction` TextDirection: Actual paragraph direction. (anything other than Rtl is placed left to right)
  - `measure_width` &mut dyn FnMut(&str, &str) -> f64: Function that takes (font string, text) and returns the width.
  - returns RichTextLayout: Layout result.

  Example: In a right to left paragraph the earlier segment comes on the right

  ```rust
  use vanilla::{RichText, TextAlign, TextDirection, Vector2};
  
  let mut measure_width = |_font_string: &str, text: &str| -> f64 {
  	text.chars().count() as f64 * 10.0
  };
  let mut rich_text = RichText::create_with_text("ab<b>cd</b>", 20.0);
  rich_text.set_text_align(TextAlign::Start);
  let left_to_right_layout = rich_text.layout_segments(Vector2::create(200.0, 40.0), TextDirection::Ltr, &mut measure_width);
  assert_eq!(left_to_right_layout.run_list[0].x, 0.0);
  assert_eq!(left_to_right_layout.run_list[1].x, 20.0);
  assert_eq!(left_to_right_layout.run_list[1].font_string, "bold 20px default");
  let right_to_left_layout = rich_text.layout_segments(Vector2::create(200.0, 40.0), TextDirection::Rtl, &mut measure_width);
  assert_eq!(right_to_left_layout.run_list[0].x, 180.0);
  assert_eq!(right_to_left_layout.run_list[1].x, 160.0);
  ```

- `pub fn calculate_intrinsic_content_size(&self, measure_width: &mut dyn FnMut(&str, &str) -> f64) -> Vector2` (method, since 0.3.2): Intrinsic size of the text. (with segments, combined width x largest font size, otherwise plain text width x font size. The original getIntrinsicContentSize)
  - `measure_width` &mut dyn FnMut(&str, &str) -> f64: Function that takes (font string, text) and returns the width.
  - returns Vector2: (width, height).

  Example: With segments, the combined width and the largest font size

  ```rust
  use vanilla::{RichText, Vector2};
  
  let mut measure_width = |_font_string: &str, text: &str| -> f64 {
  	text.chars().count() as f64 * 10.0
  };
  let mut rich_text = RichText::create_with_text("ab<size=40>cd</size>", 20.0);
  assert_eq!(rich_text.calculate_intrinsic_content_size(&mut measure_width), Vector2::create(40.0, 40.0));
  rich_text.set_text("plain");
  assert_eq!(rich_text.calculate_intrinsic_content_size(&mut measure_width), Vector2::create(50.0, 20.0));
  ```

- `pub fn resolve_segment_text_direction(&self, graphic: &Graphic) -> TextDirection` (method, since 0.4.0): Actual direction of the joined segment text. (the contained Text's direction, the Graphic's direction if Inherit. Auto uses the first strong character of the joined text)
  - `graphic` &Graphic: Graphic to look at when the direction is Inherit.
  - returns TextDirection: Ltr or Rtl.
- `pub fn set_text_direction(&mut self, text_direction: TextDirection)` (method, since 0.4.0): Sets the text direction. (forwarded to the contained Text, the original setTextDirection)
  - `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.
- `pub fn set_visible_character_count(&mut self, visible_character_count: i32)` (method, since 0.4.0): Sets the visible character count. (forwarded to the contained Text, -1 for all. Text with markup is not cut, as in the original)
  - `visible_character_count` i32: Number of visible character clusters. (-1 for all)
- `pub fn get_visible_character_count(&self) -> i32` (method, since 0.4.0): Returns the visible character count.
  - returns i32: Number of visible character clusters. (-1 for all)
- `pub fn draw_segments(&self, graphic: &mut Graphic, content_size: Vector2)` (method, since 0.3.2): Draws segments. (the original drawSegments)
  - `graphic` &mut Graphic: Graphic to draw to. (draws while changing paragraph direction, alignment, baseline, font string and color)
  - `content_size` Vector2: Node content size.

## Functions and constants

- `pub fn build_font_string(font_family: &str, font_size: f64, is_bold: bool, is_italic: bool) -> String` (method, since 0.3.2): String in Canvas2D font form. (build_font_string in the original text.js)
  - `font_family` &str: Font name.
  - `font_size` f64: Font size. (pixels)
  - `is_bold` bool: If true, includes bold.
  - `is_italic` bool: If true, includes italic.
  - returns String: Font string.

  Example: In the order italic, bold, size, name

  ```rust
  use vanilla::core::component::richtext::build_font_string;
  
  assert_eq!(build_font_string("default", 20.0, false, false), "20px default");
  assert_eq!(build_font_string("GameFont", 16.5, true, true), "italic bold 16.5px GameFont");
  ```

- `pub fn parse_markup_to_segments(input: &str) -> Option<Vec<RichTextSegment>>` (method, since 0.3.2): Markup → segment list. (None if there are no known tags at all. The original parseMarkupToSegments)
  - Unknown opening tags remain as text. Closing tags are removed from the text even without a match. (same as the original)
  - `input` &str: Markup text.
  - returns Option<Vec<RichTextSegment>>: List of segments. None if there are no known tags at all (also for empty text and text without `<`).

  Example: Unknown tags remain as text

  ```rust
  use vanilla::core::component::richtext::parse_markup_to_segments;
  
  assert!(parse_markup_to_segments("plain text").is_none());
  assert!(parse_markup_to_segments("a < b and <unknown>tag</unknown>").is_none());
  let segment_list = parse_markup_to_segments("<u>x</u><foo>y").expect("segments");
  let text_list: Vec<&str> = segment_list.iter().map(|segment| segment.text.as_str()).collect();
  assert_eq!(text_list, vec!["x", "<foo>", "y"]);
  assert!(segment_list[0].attributes.is_underline);
  ```

