# misc/typewriter (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/misc/typewriter/

Typewriter effect.
- A port of the original misc/typewriter.js. Reveals the text of a target that can set its visible character count, like Text, one character at a time at a set speed per second.
  (visual novel / RPG dialogue presentation)
- Usage:
  ```text
    let mut typewriter = Typewriter::new(TypewriterOptions { characters_per_second: 30.0, ..TypewriterOptions::default() });
    let label = node_tree[label_id].get_component_mut::<Text>().unwrap();
    typewriter.start(label, Some("Hello. The adventure begins."));
    // every frame: typewriter.tick(label, time_delta);
    // on input: next line if finished (typewriter.is_finished()), otherwise typewriter.skip_to_end(label)
  ```
- Differences from the original:
  The original takes the target in the constructor and holds it. The Rust version cannot hold a component inside a node, so
  the target (&mut dyn TypewriterTarget) is passed on every start / tick / skip_to_end. Text implements TypewriterTarget.
  As in the original, characters are counted in grapheme clusters (final consonants, combining marks, and emoji sequences count as one). The character reveal notification receives (grapheme cluster, index).
  The options object is the TypewriterOptions struct.

## TypewriterTarget (trait)

Typewriter target. (set text, return text, set visible character count. -1 means all)
- Implemented by Text. Other text renderers can be revealed by Typewriter if they implement this.

Example: A target that only remembers the visible character count

```rust
use vanilla::{Typewriter, TypewriterOptions, TypewriterTarget};

struct CountingLabel {
	text: String,
	visible_character_count: i32,
}

impl TypewriterTarget for CountingLabel {
	fn set_text(&mut self, text: &str) {
		self.text = text.to_string();
	}

	fn get_text(&self) -> &str {
		&self.text
	}

	fn set_visible_character_count(&mut self, visible_character_count: i32) {
		self.visible_character_count = visible_character_count;
	}
}

let mut label = CountingLabel {
	text: String::new(),
	visible_character_count: -1,
};
let mut typewriter = Typewriter::new(TypewriterOptions {
	characters_per_second: 10.0,
	..TypewriterOptions::default()
});
typewriter.start(&mut label, Some("hello"));
typewriter.tick(&mut label, 0.25);
assert_eq!(label.visible_character_count, 2);
```

- `fn set_text(&mut self, text: &str)` (method, since 0.3.2): Sets the text.
  - `text` &str: New text.
- `fn get_text(&self) -> &str` (method, since 0.3.2): Returns the text.
  - returns &str: The current full text. (regardless of the visible character count)
- `fn set_visible_character_count(&mut self, visible_character_count: i32)` (method, since 0.3.2): Sets the visible character count. (-1 means all)
  - `visible_character_count` i32: Number of grapheme clusters visible from the start. (-1 means all)

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

Typewriter settings. (original options = { characters_per_second = 30, fast_forward_multiplier = 8 })

Example: Change only the speed

```rust
use vanilla::{Typewriter, TypewriterOptions};

let typewriter_options = TypewriterOptions {
	characters_per_second: 20.0,
	..TypewriterOptions::default()
};
assert_eq!(typewriter_options.fast_forward_multiplier, 8.0);
let typewriter = Typewriter::new(typewriter_options);
assert!(typewriter.is_finished());
```

- `pub characters_per_second: f64` (field, since 0.3.2): Characters per second.
  - returns f64
- `pub fast_forward_multiplier: f64` (field, since 0.3.2): Multiplier applied when fast forwarding.
  - returns f64

## Typewriter (struct) (Default)

Typewriter effect.
- Pass the target and text with start, and pass the same target to tick every frame. On input, go to the next line if finished, otherwise skip_to_end.

Example: Reveal a line in a node's Text

```rust
use vanilla::{NodeTree, Text, Typewriter, TypewriterOptions};

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].add_component(Text::new());

let mut typewriter = Typewriter::new(TypewriterOptions {
	characters_per_second: 30.0,
	..TypewriterOptions::default()
});
let label = node_tree[label_id].get_component_mut::<Text>().unwrap();
typewriter.start(label, Some("Hello. The adventure begins."));
typewriter.tick(label, 0.1);
assert_eq!(label.get_visible_character_count(), 3);

if typewriter.is_finished() {
	typewriter.start(label, Some("Next line."));
}
else {
	typewriter.skip_to_end(label);
}
assert!(typewriter.is_finished());
assert_eq!(label.get_visible_character_count(), -1);
```

- `pub fn new(options: TypewriterOptions) -> Typewriter` (constructor, since 0.3.2): Constructor. (finished state initially)
  - `options` TypewriterOptions: Characters per second and fast forward multiplier.
  - returns Typewriter: A new typewriter with no text, in the finished state.
- `pub fn start(&mut self, target: &mut dyn TypewriterTarget, text: Option<&str>)` (method, since 0.3.2): Starts. (if text is passed, also changes the target's text. Otherwise uses the target's current text. An empty text is immediately finished)
  - Sets the target's visible character count to 0 and turns fast forward off. For an empty text, leaves it at -1 (all). The completion notification is not called.
  - `target` &mut dyn TypewriterTarget: Target to reveal the text in.
  - `text` Option<&str>: New text to put in. None uses the target's current text.
- `pub fn tick(&mut self, target: &mut dyn TypewriterTarget, time_delta: f64)` (method, since 0.3.2): Update. (reveals as many characters as accumulated and notifies for each newly revealed character. Finishes when everything is revealed)
  - Does nothing after finishing. When everything is revealed, sets the visible character count to -1 and notifies completion.
  - `target` &mut dyn TypewriterTarget: The target passed to start.
  - `time_delta` f64: Elapsed time. (seconds, accumulates characters per second * multiplier * time_delta)

  Example: Get a notification for each revealed character

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Text, Typewriter, TypewriterOptions};
  
  let revealed_list = Rc::new(RefCell::new(Vec::new()));
  let revealed_list_for_event = revealed_list.clone();
  let mut label = Text::new();
  let mut typewriter = Typewriter::new(TypewriterOptions {
  	characters_per_second: 10.0,
  	..TypewriterOptions::default()
  });
  typewriter.set_character_revealed_event(move |character, character_index| {
  	revealed_list_for_event.borrow_mut().push((character.to_string(), character_index));
  });
  typewriter.start(&mut label, Some("abc"));
  typewriter.tick(&mut label, 0.25);
  assert_eq!(*revealed_list.borrow(), vec![(String::from("a"), 0), (String::from("b"), 1)]);
  ```

- `pub fn skip_to_end(&mut self, target: &mut dyn TypewriterTarget)` (method, since 0.3.2): Reveals everything immediately. (reveal notifications for unrevealed characters are not called)
  - Does nothing if finished. Otherwise sets the visible character count to -1 and notifies completion.
  - `target` &mut dyn TypewriterTarget: The target passed to start.
- `pub fn is_finished(&self) -> bool` (method, since 0.3.2): Whether it has finished.
  - returns bool: true if all the text has been revealed or start has not been called yet.
- `pub fn set_fast_forward(&mut self, is_fast_forward: bool)` (method, since 0.3.2): Sets fast-forward. (while held, etc.)
  - `is_fast_forward` bool: If true, multiplies the speed by the fast forward multiplier. (returns to false on start)
- `pub fn set_characters_per_second(&mut self, characters_per_second: f64)` (method, since 0.3.2): Sets the speed. (characters per second)
  - `characters_per_second` f64: Number of grapheme clusters revealed per second.
- `pub fn set_character_revealed_event(&mut self, character_revealed_event: impl FnMut(&str, usize) + 'static)` (method, since 0.3.2): Sets the character reveal notification. (character, index)
  - `character_revealed_event` impl FnMut(&str, usize) + 'static: Function to call each time a character is revealed. Receives that grapheme cluster and its index counted from 0.
- `pub fn set_complete_event(&mut self, complete_event: impl FnMut() + 'static)` (method, since 0.3.2): Sets the finish callback.
  - `complete_event` impl FnMut() + 'static: Function to call when everything is revealed or skip_to_end is called.
