# animation/timeline (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/animation/timeline/

Timeline. (keyframe animation document player)
- A port of the original animation/timeline.js. The document (description) is JSON made of a stage node list + tracks (target name / property / keys) + markers,
  saved by the timeline editor. A key's easing applies to the span from that key to the next key.
- Easing curves use easing_function from core/tween.rs as is. "bezier" uses the same control points as CSS cubic-bezier.
- Usage:
  ```text
    // Request the document in the scene's create and hand it over.
    self.timeline_asset.load(engine, "assets/intro.timeline.json");
    self.scene_base.track_asset(&self.timeline_asset);
    // Build the stage in initialize and play it.
    let mut timeline = Timeline::create_from_json_asset(&mut self.timeline_asset).unwrap_or_default();
    let stage_id = self.scene_base.get_root_id();
    timeline.build_stage(self.scene_base.get_node_tree_mut(), stage_id, Some(&|image_name: &str| image_table.get(image_name).cloned()));
    timeline.play();
    // Every frame (tick):
    timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
  ```
- Differences from the original:
  - Targets are TimelineTarget instead of object references. Nodes are Node(NodeId), and things that are not nodes (such as screen effects) are External(`Rc<RefCell<dyn TimelinePropertyTarget>>`).
    Functions that act on nodes (tick, seek, stop, evaluate, compile, build_stage, bind) also take the NodeTree.
  - For External targets, evaluate calls set_timeline_property right there, as in the original. (the scene shares the target as `Rc<RefCell>`)
    The receiving side implements the TimelinePropertyTarget trait. ScreenEffect implements it in this file.
    Values the last evaluate applied to External targets can be read with get_external_properties. (for editors and tests)
  - Values hold the original's number / string / boolean as the TimelineValue enum. Numbers are f64.
  - Handlers take the timeline itself (&mut Timeline) as the last argument as in the original, followed by the NodeTree to pass to node functions.
    The handler is taken out of its slot while it is called, so pause, seek and set_*_handler can be called inside a handler. (a newly set handler wins)
  - Text properties (text, number, fontSize, visibleCharacters, color) also apply to RichText nodes, just as the original getComponent(Text) also finds RichText, which inherits Text.
  - resolve_timeline_easing returns a TimelineEasing value instead of a function. (call it with evaluate(progress))
  - TIMELINE_PROPERTY_DEFINITIONS is an array of definitions instead of a name → definition object, searched with find_timeline_property_definition.
    TIMELINE_NODE_DEFAULTS is a TimelineNodeDescription filled with the defaults. (the original key type is node_type)
  - The original's sprite grid table and sound table (WeakMap) became small components attached to nodes, TimelineSpriteFrameGrid and TimelineSound.
  - The original Timeline.setAudioManager (static) and the asynchronous loading of sound nodes became load_sounds(node_tree, engine).
    Calling it once after building the stage loads an audio asset and creates a player for each sound node. (the scene may take over the returned assets with track_audio_asset)
  - loadFromUrl (asynchronous fetch) is load_from_url(engine, asset path). It asks for the bytes through the engine's asset fetching, and awaiting it inside an engine task yields the timeline.
    (desktop uses the asset folder candidates, web fetches from asset_base_url) Without await, pass a document received with JsonAsset to create_from_json_asset / load_from_text.
  - "data:" URL images: on the web, as in the original, the browser decodes them (fetch and HTMLImageElement, platform/web.rs), and once decoded they are set on the sprite and the description's cell is picked again.
    (the original image.onload's applySpriteFrame; meanwhile TimelineSpriteFrameGrid waits and updates)
    On desktop they are decoded right there. Like a browser, it first decodes percent forms (%XX) in the body, and decodes base64 if ;base64. If the URL's type is image/svg+xml it is an SVG drawn with resvg,
    otherwise a raster identified by its content (png, jpeg, webp, gif, bmp, ico, avif). (Image::load_from_memory_with_mime_type)
- Easing curve values are the same as the original. If two stage nodes have the same name, both are attached and the later one stays in the name table (same as the original).
  If a parent is itself or forms a cycle, the node is attached to the stage parent. load_from_text and create_from_json_asset also exist in the original.

## TimelinePropertyDefinition (struct) (Clone, Copy, Debug)

Property definition. (name → kind / display name / function applied to the node)
- Stored in TIMELINE_PROPERTY_DEFINITIONS. Properties with no definition are not applied to nodes and are passed only to External targets.

Example: Find the opacity definition and apply it to a node

```rust
use vanilla::{find_timeline_property_definition, TimelinePropertyKind, TimelineValue, WorldNode};

let definition = find_timeline_property_definition("opacity").expect("opacity");
assert_eq!(definition.kind, TimelinePropertyKind::Number);
assert_eq!(definition.label, "Opacity");
let mut node = WorldNode::new("box");
if let Some(apply) = definition.apply {
	apply(&mut node, &TimelineValue::Number(1.5));
}
assert_eq!(node.get_local_opacity(), 1.0);
assert!(find_timeline_property_definition("event").is_some_and(|definition| definition.apply.is_none()));
```

- `pub name: &'static str` (field, since 0.3.2): Property name of the description track. (the original name as is, like "scaleX")
  - returns &'static str
- `pub kind: TimelinePropertyKind` (field, since 0.3.2): Value kind. (decides the interpolation method)
  - returns TimelinePropertyKind
- `pub label: &'static str` (field, since 0.3.2): Name shown in the editor.
  - returns &'static str
- `pub apply: Option<fn(&mut WorldNode, &TimelineValue)>` (field, since 0.3.2): Function that applies the value to a node. If None, it is not applied to nodes. ("event")
  - returns Option<fn(&mut WorldNode, &TimelineValue)>

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

One key. (time, value, easing from this key to the next key, bezier control points)

Example: Two keys going from 0 to 100 with quadratic.in

```rust
use serde_json::json;
use vanilla::{Timeline, TimelineKey, TimelinePropertyKind, TimelineValue};

let mut start_key = TimelineKey::new(0.0, TimelineValue::Number(0.0));
start_key.easing = String::from("quadratic.in");
let end_key = TimelineKey::from_json(&json!({ "time": 2, "value": 100 }));
let keys = vec![start_key, end_key];
assert_eq!(Timeline::sample_keys(&keys, TimelinePropertyKind::Number, 1.0), TimelineValue::Number(25.0));
assert_eq!(Timeline::sample_keys(&keys, TimelinePropertyKind::Number, 3.0), TimelineValue::Number(100.0));
```

- `pub time: f64` (field, since 0.3.2): Key time. (seconds)
  - returns f64
- `pub value: TimelineValue` (field, since 0.3.2): Key value.
  - returns TimelineValue
- `pub easing: String` (field, since 0.3.2): Easing name of the span from this key to the next key. (empty strings and unknown names are linear)
  - returns String
- `pub curve: Option<Vec<f64>>` (field, since 0.3.2): Control points [x1, y1, x2, y2] when easing is "bezier". (ease-in-out if None)
  - returns Option<Vec<f64>>
- `pub fn new(time: f64, value: TimelineValue) -> TimelineKey` (constructor, since 0.3.2): Constructor. (easing linear)
  - `time` f64: Key time. (seconds)
  - `value` TimelineValue: Key value.
  - returns TimelineKey: A key with easing "linear" and no control points.
- `pub fn from_json(key_description: &Value) -> TimelineKey` (static, since 0.3.2): Creates from a JSON key. ({ time, value, easing, curve })
  - `key_description` &Value: Description key object. (a missing time is 0, value is None, easing is an empty string, curve is None. Non-number entries of curve are 0)
  - returns TimelineKey: The read key.
- `pub fn resolve_easing(&self) -> TimelineEasing` (method, since 0.3.2): Easing of the span starting at this key.
  - returns TimelineEasing: Easing chosen from easing and curve. (same as resolve_timeline_easing)

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

Marker. (time and name. The marker handler is called when it is passed)

Example: Play for 1 second and receive the markers passed

```rust
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineMarker};

let passed_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"loop": false,
	"markers": [{ "time": 0.5, "name": "hit" }, { "time": 1.5, "name": "end" }],
})));
let recorded_list = passed_list.clone();
timeline.set_marker_handler(Some(Box::new(move |marker_name: &str, marker: &TimelineMarker, _timeline: &mut Timeline, _node_tree: &mut NodeTree| {
	recorded_list.borrow_mut().push(format!("{} {}", marker_name, marker.time));
})));
timeline.play();
timeline.tick(&mut node_tree, 1.0);
assert_eq!(*passed_list.borrow(), vec![String::from("hit 0.5")]);
```

- `pub time: f64` (field, since 0.3.2): Marker time. (seconds)
  - returns f64
- `pub name: String` (field, since 0.3.2): Marker name.
  - returns String

## TimelinePropertyTarget (trait)

Trait for targets that are not nodes to receive values. (the original setTimelineProperty(name, value))
- Hold it as `Rc<RefCell<..>>` and register it as TimelineTarget::External, and evaluate calls it right there.

Example: Fade target receiving track values

```rust
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelinePropertyTarget, TimelineTarget, TimelineValue};

struct Fader {
	alpha: f64,
}

impl TimelinePropertyTarget for Fader {
	fn set_timeline_property(&mut self, property_name: &str, value: &TimelineValue) {
		if property_name == "alpha" {
			self.alpha = value.as_number();
		}
	}
}

let fader: Rc<RefCell<Fader>> = Rc::new(RefCell::new(Fader { alpha: 0.0 }));
let fader_target: Rc<RefCell<dyn TimelinePropertyTarget>> = fader.clone();
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"tracks": [{ "target": "fader", "property": "alpha", "keys": [{ "time": 0, "value": 0 }, { "time": 2, "value": 1 }] }],
})));
timeline.set_target("fader", TimelineTarget::External(fader_target));
timeline.evaluate(&mut node_tree, 1.0);
assert_eq!(fader.borrow().alpha, 0.5);
```

- `fn set_timeline_property(&mut self, property_name: &str, value: &TimelineValue)` (method, since 0.3.2): Receives a property value.
  - `property_name` &str: Property name of the description track.
  - `value` &TimelineValue: Value sampled at that time.

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

One value applied to an External target. (get_external_properties)

Example: Read the values applied to External targets after evaluate

```rust
use std::cell::RefCell;
use std::rc::Rc;
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineExternalProperty, TimelinePropertyTarget, TimelineTarget, TimelineValue};

struct Silent;

impl TimelinePropertyTarget for Silent {
	fn set_timeline_property(&mut self, _property_name: &str, _value: &TimelineValue) {
	}
}

let screen: Rc<RefCell<dyn TimelinePropertyTarget>> = Rc::new(RefCell::new(Silent));
let mut node_tree = NodeTree::new();
let mut timeline = Timeline::new(Some(json!({
	"duration": 2,
	"tracks": [{ "target": "screen", "property": "vignette", "keys": [{ "time": 0, "value": 0 }, { "time": 2, "value": 1 }] }],
})));
timeline.set_target("screen", TimelineTarget::External(screen));
timeline.evaluate(&mut node_tree, 1.0);
let expected_property = TimelineExternalProperty {
	target_name: String::from("screen"),
	property_name: String::from("vignette"),
	value: TimelineValue::Number(0.5),
};
assert_eq!(timeline.get_external_properties(), &[expected_property]);
```

- `pub target_name: String` (field, since 0.3.2): Track target name.
  - returns String
- `pub property_name: String` (field, since 0.3.2): Track property name.
  - returns String
- `pub value: TimelineValue` (field, since 0.3.2): The applied value.
  - returns TimelineValue

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

Description node. (the original stage node description. TIMELINE_NODE_DEFAULTS holds the defaults)
- Field names are snake_case, and keys of the description JSON are camelCase as in the original. (scale_x ← "scaleX")

Example: Read description JSON over the defaults

```rust
use serde_json::json;
use vanilla::{TimelineNodeDescription, TIMELINE_NODE_DEFAULTS};

let description = TimelineNodeDescription::from_json(&json!({ "name": "Box", "type": "paint", "x": 40, "scaleX": 2, "visible": false }));
assert_eq!(description.node_type, "paint");
assert_eq!(description.x, 40.0);
assert_eq!(description.scale_x, 2.0);
assert!(!description.visible);
assert_eq!(description.width, TIMELINE_NODE_DEFAULTS.width);
assert_eq!(description.color, "#ffffffff");
```

- `pub name: String` (field, since 0.3.2): Node name. (a track's target points to this name, default empty string)
  - returns String
- `pub node_type: String` (field, since 0.3.2): The original key type. ("group", "paint", "sprite", "text", "particle", "sound")
  - returns String
- `pub parent: Option<String>` (field, since 0.3.2): Parent node name. (if None, attached to the stage parent)
  - returns Option<String>
- `pub x: f64` (field, since 0.3.2): Local x position. (relative to the parent's top left, default 0)
  - returns f64
- `pub y: f64` (field, since 0.3.2): Local y position. (default 0)
  - returns f64
- `pub width: f64` (field, since 0.3.2): Content width. (default 100)
  - returns f64
- `pub height: f64` (field, since 0.3.2): Content height. (default 100)
  - returns f64
- `pub scale_x: f64` (field, since 0.3.2): Horizontal scale. (JSON "scaleX", default 1)
  - returns f64
- `pub scale_y: f64` (field, since 0.3.2): Vertical scale. (JSON "scaleY", default 1)
  - returns f64
- `pub rotation: f64` (field, since 0.3.2): Rotation. (degrees, default 0)
  - returns f64
- `pub opacity: f64` (field, since 0.3.2): Opacity. (0 ~ 1, default 1)
  - returns f64
- `pub pivot_x: f64` (field, since 0.3.2): Pivot x ratio. (JSON "pivotX", 0 ~ 1, default 0.5)
  - returns f64
- `pub pivot_y: f64` (field, since 0.3.2): Pivot y ratio. (JSON "pivotY", 0 ~ 1, default 0.5)
  - returns f64
- `pub visible: bool` (field, since 0.3.2): Visible. (turned off only when the JSON is false, default true)
  - returns bool
- `pub color: String` (field, since 0.3.2): Color string. (fill color for paint, text color for text, tint color for sprite. default "#ffffffff")
  - returns String
- `pub round_size: f64` (field, since 0.3.2): paint corner rounding size. (JSON "roundSize", default 0)
  - returns f64
- `pub image: String` (field, since 0.3.2): sprite image name. (passed to the image resolver. A "data:" URL is decoded right there, default empty string)
  - returns String
- `pub frame_columns: f64` (field, since 0.3.2): Number of sprite sheet columns. (JSON "frameColumns", 1 if less than 1, default 1)
  - returns f64
- `pub frame_rows: f64` (field, since 0.3.2): Number of sprite sheet rows. (JSON "frameRows", 1 if less than 1, default 1)
  - returns f64
- `pub frame: f64` (field, since 0.3.2): Initial sprite sheet cell index. (rounded, default 0)
  - returns f64
- `pub effect: String` (field, since 0.3.2): sprite ShaderSprite effect name. (ShaderSpriteEffect::from_name, unknown names mean no effect, default "none")
  - returns String
- `pub effect_progress: f64` (field, since 0.3.2): sprite effect progress. (JSON "effectProgress", 0 ~ 1, default 0)
  - returns f64
- `pub effect_color: String` (field, since 0.3.2): sprite effect color string. (JSON "effectColor", the effect's default color if empty, default empty string)
  - returns String
- `pub blend_mode: String` (field, since 0.3.2): sprite blend name. (JSON "blendMode", canvas composite name, unknown names are Normal, default "source-over")
  - returns String
- `pub text: String` (field, since 0.3.2): text string. (default "Text")
  - returns String
- `pub font_size: f64` (field, since 0.3.2): text font size. (JSON "fontSize", pixels, default 32)
  - returns f64
- `pub bold: bool` (field, since 0.3.2): text bold. (only when the JSON is true, default false)
  - returns bool
- `pub text_align: String` (field, since 0.3.2): text horizontal alignment name. (JSON "textAlign", "left", "right", "start", "end", anything else is center. default "center")
  - returns String
- `pub particle: Option<Value>` (field, since 0.3.2): particle description object. (passed to ParticleSystem::apply_description, None if null)
  - returns Option<Value>
- `pub audio: String` (field, since 0.3.2): sound audio URL. (read by Timeline::load_sounds, default empty string)
  - returns String
- `pub volume: f64` (field, since 0.3.2): sound volume. (only held, default 1)
  - returns f64
- `pub fn from_json(node_description: &Value) -> TimelineNodeDescription` (static, since 0.3.2): Creates from a JSON description. (the given entries overwrite the defaults. The original Object.assign({}, TIMELINE_NODE_DEFAULTS, description))
  - Entries of the wrong shape keep the default. visible is turned off only when false, as in the original.
  - `node_description` &Value: Node object from the description's stage.nodes.
  - returns TimelineNodeDescription: Description node filled with defaults.

## TimelineSpriteFrameGrid (struct) (Component)

Sprite sheet grid. (frame_columns / frame_rows of the node description. In place of the original spriteFrameGridTable)
- A display component that does not draw. The frame property reads this to pick a cell.
- Updates only while the browser decodes a "data:" URL image on the web. Once decoded, it sets it on the sprite and picks the description's cell. (the original image.onload's applySpriteFrame)

Example: A sprite node with cell 5 of a 4 x 2 sheet picked

```rust
use std::rc::Rc;
use serde_json::json;
use vanilla::{Image, NodeTree, Rect, ShaderSprite, Timeline, TimelineSpriteFrameGrid};

let sheet_image = Image::create_from_pixels(64, 32, vec![255u8; 64 * 32 * 4]);
let image_resolver = |image_name: &str| -> Option<Rc<Image>> {
	if image_name == "coin" {
		Some(sheet_image.clone())
	}
	else {
		None
	}
};
let mut node_tree = NodeTree::new();
let node_description = json!({ "name": "Coin", "type": "sprite", "image": "coin", "frameColumns": 4, "frameRows": 2, "frame": 5 });
let coin_id = Timeline::create_stage_node(&mut node_tree, &node_description, Some(&image_resolver));
let frame_grid = node_tree[coin_id].get_component::<TimelineSpriteFrameGrid>().expect("grid");
assert_eq!((frame_grid.get_columns(), frame_grid.get_rows()), (4, 2));
let image_rect = node_tree[coin_id].get_component::<ShaderSprite>().expect("sprite").get_sprite().get_image_rect();
assert_eq!(image_rect, Rect::create(16.0, 16.0, 16.0, 16.0));
```

- `pub fn new(columns: usize, rows: usize) -> TimelineSpriteFrameGrid` (constructor, since 0.3.2): Constructor. (cell counts are at least 1)
  - `columns` usize: Number of columns. (1 if 0)
  - `rows` usize: Number of rows. (1 if 0)
  - returns TimelineSpriteFrameGrid: A grid component with no image waiting.
- `pub fn set_grid(&mut self, columns: usize, rows: usize)` (method, since 0.3.2): Sets the grid.
  - Does not re-pick the current cell. The new grid is used from the next frame value.
  - `columns` usize: Number of columns. (1 if 0)
  - `rows` usize: Number of rows. (1 if 0)
- `pub fn get_columns(&self) -> usize` (method, since 0.3.2): Number of columns.
  - returns usize: Number of columns. (at least 1)
- `pub fn get_rows(&self) -> usize` (method, since 0.3.2): Number of rows.
  - returns usize: Number of rows. (at least 1)

## TimelineSound (struct) (Default, Component)

Sound node state. (in place of the original soundPlayerTable's { audio_player, audio_asset, audio_source, volume })
- The asset and player are filled by Timeline::load_sounds. The event keys play / loop / stop drive the player.

Example: A newly created sound node holds only the URL and volume

```rust
use serde_json::json;
use vanilla::{NodeTree, Timeline, TimelineSound};

let mut node_tree = NodeTree::new();
let node_description = json!({ "name": "Hit", "type": "sound", "audio": "tests/assets/audio/wav_s16_stereo.wav", "volume": 0.5 });
let sound_id = Timeline::create_stage_node(&mut node_tree, &node_description, None);
let sound = node_tree[sound_id].get_component::<TimelineSound>().expect("sound");
assert_eq!(sound.get_audio_source(), "tests/assets/audio/wav_s16_stereo.wav");
assert_eq!(sound.get_volume(), 0.5);
assert!(sound.get_audio_asset().is_none());
```

- `pub fn new() -> TimelineSound` (constructor, since 0.3.2): Constructor. (empty)
  - returns TimelineSound: A sound component with an empty URL, volume 1, and no asset or player.
- `pub fn get_audio_source(&self) -> &str` (method, since 0.3.2): Returns the audio URL.
  - returns &str: The description's audio URL. (empty string if none)
- `pub fn get_volume(&self) -> f64` (method, since 0.3.2): Returns the volume. (only holds the description value, as in the original)
  - returns f64: The description's volume. (default 1, not applied to the player)
- `pub fn get_audio_asset(&self) -> Option<&Rc<AudioAsset>>` (method, since 0.3.2): Returns the audio asset.
  - returns Option<&Rc<AudioAsset>>: The loaded audio asset. None before load_sounds or if loading failed.
- `pub fn get_audio_player_mut(&mut self) -> Option<&mut AudioPlayer>` (method, since 0.3.2): Returns the player.
  - returns Option<&mut AudioPlayer>: Mutable reference to the player. None before load_sounds.
- `pub fn stop(&mut self)` (method, since 0.3.2): Stops. (if there is a player)

## TimelineEventHandler (type)

Event handler. ((target name, event name, key, timeline, node tree))

```rust
pub type TimelineEventHandler = Box<dyn FnMut(&str, &str, &TimelineKey, &mut Timeline, &mut NodeTree)>
```

## TimelineMarkerHandler (type)

Marker handler. ((marker name, marker, timeline, node tree))

```rust
pub type TimelineMarkerHandler = Box<dyn FnMut(&str, &TimelineMarker, &mut Timeline, &mut NodeTree)>
```

## TimelineCompleteHandler (type)

Completion handler. ((timeline, node tree))

```rust
pub type TimelineCompleteHandler = Box<dyn FnMut(&mut Timeline, &mut NodeTree)>
```

## TimelineTargetResolver (type)

Target resolver. (name → target)

```rust
pub type TimelineTargetResolver = Box<dyn Fn(&str) -> Option<TimelineTarget>>
```

## TimelineImageResolver (type)

Image resolver. (image name → image)

```rust
pub type TimelineImageResolver<'a> = &'a dyn Fn(&str) -> Option<Rc<Image>>
```

## Timeline (struct) (Default)

Timeline.
- Holds a description (JSON), and after building a stage (build_stage) or binding to existing nodes (bind), plays it with tick.

Example: Build a stage and move a box to the right over 2 seconds

```rust
use serde_json::json;
use vanilla::{NodeTree, Timeline, Vector2};

let description = json!({
	"duration": 2,
	"loop": false,
	"stage": { "nodes": [{ "name": "Box", "type": "paint", "width": 40, "height": 40, "color": "#ff0000ff" }] },
	"tracks": [{ "target": "Box", "property": "x", "keys": [{ "time": 0, "value": 0 }, { "time": 2, "value": 200 }] }],
});
let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let mut timeline = Timeline::new(Some(description));
let node_table = timeline.build_stage(&mut node_tree, root_id, None);
let box_id = node_table["Box"];
timeline.play();
timeline.tick(&mut node_tree, 0.5);
assert_eq!(node_tree[box_id].get_local_position(), Vector2::create(50.0, 0.0));
timeline.tick(&mut node_tree, 2.0);
assert!(!timeline.is_playing());
assert_eq!(timeline.get_time(), 2.0);
assert_eq!(node_tree[box_id].get_local_position().x, 200.0);
```

Example: Build the stage in the scene's initialize and play it in tick

```rust
use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, Timeline};

const INTRO_TIMELINE: &str = r#"{
	"duration": 3,
	"loop": true,
	"stage": { "nodes": [{ "name": "Logo", "type": "text", "text": "Vanilla" }] },
	"tracks": [{ "target": "Logo", "property": "opacity", "keys": [{ "time": 0, "value": 0 }, { "time": 1, "value": 1 }] }]
}"#;

struct IntroScene {
	scene_base: SceneBase,
	timeline: Timeline,
}

impl Scene for IntroScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn initialize(&mut self, _engine: &Engine) {
		self.timeline = Timeline::load_from_text(INTRO_TIMELINE).unwrap_or_default();
		let stage_id = self.scene_base.get_root_id();
		self.timeline.build_stage(self.scene_base.get_node_tree_mut(), stage_id, None);
		self.timeline.play();
	}

	fn tick(&mut self, time_delta: f64) {
		self.scene_base.tick(time_delta);
		self.timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
	}
}

let engine = Engine::new(EngineConfiguration::new());
let intro_scene = IntroScene {
	scene_base: SceneBase::new(),
	timeline: Timeline::default(),
};
engine.run(Box::new(intro_scene)).unwrap();
```

- `pub fn new(description: Option<Value>) -> Timeline` (constructor, since 0.3.2): Constructor. (an empty description if none is given)
  - `description` Option<Value>: Description JSON. If None or not an object, an empty description (create_empty_description); missing stage, stage.nodes, tracks and markers are filled in.
  - returns Timeline: A stopped timeline. (time 0, speed 1, compiled on first use)
- `pub fn create_empty_description() -> Value` (static, since 0.3.2): Creates an empty description. (static)
  - returns Value: A description named "Timeline", 3 seconds long, 30 frames per second, looping, with a 960 x 540 stage (background "#101114ff") and no nodes, tracks or markers.
- `pub fn load_from_text(text: &str) -> Result<Timeline, String>` (static, since 0.3.2): Creates from a JSON string. (in place of after response.json() in the original loadFromUrl)
  - `text` &str: Description JSON string.
  - returns Result<Timeline, String>: The timeline of that description. Err with the reason if it cannot be read as JSON.

  Example: Create from a JSON string, and failure

  ```rust
  use vanilla::Timeline;
  
  let timeline = Timeline::load_from_text(r#"{ "duration": 1.5, "loop": false }"#).expect("timeline");
  assert_eq!(timeline.get_duration(), 1.5);
  assert!(!timeline.is_loop());
  assert!(Timeline::load_from_text("{ broken").is_err());
  ```

- `pub fn load_from_url(engine: &Engine, url: &str) -> impl Future<Output = Result<Timeline, String>> + 'static` (static, since 0.4.0): Loads from a URL. (the original static await Timeline.loadFromUrl(url); requests the asset path and awaits inside an engine task)
  - On a fetch or JSON read failure, the reason. (the original rejects the Promise)
  - `engine` &Engine: Engine to request the bytes from. (the request is made right here)
  - `url` &str: Path relative to the asset folder, or a "data:" URL.
  - returns impl Future<Output = Result<Timeline, String>> + 'static: A Future that yields the timeline when awaited. Err with the reason if fetching or reading the JSON fails. (await it inside an engine task)

  Example: Hand the loading over to an engine task in the scene's create

  ```rust
  use vanilla::{Engine, Scene, SceneBase, Timeline};
  
  struct IntroScene {
  	scene_base: SceneBase,
  	timeline: Option<Timeline>,
  }
  
  impl Scene for IntroScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn load(&mut self, engine: &Engine) {
  		let timeline_future = Timeline::load_from_url(engine, "data:application/json,{\"duration\":2,\"loop\":true}");
  		let load_task_handle = engine.spawn_scene_task(self, |mut scene_context| async move {
  			match timeline_future.await {
  				Ok(timeline) => {
  					scene_context.with(move |scene, _engine| scene.timeline = Some(timeline));
  				}
  				Err(error) => {
  					eprintln!("{}", error);
  				}
  			}
  		});
  		self.scene_base.track_task(&load_task_handle);
  	}
  }
  ```

- `pub fn create_from_json_asset(json_asset: &mut JsonAsset) -> Option<Timeline>` (static, since 0.3.2): Creates from a loaded JsonAsset. (None if not loaded yet or failed)
  - `json_asset` &mut JsonAsset: Asset that loaded the description JSON. (the description is cloned)
  - returns Option<Timeline>: The timeline of that description. None if the asset is not loaded yet or could not be parsed as JSON.

  Example: None before loading, a timeline once the bytes arrive

  ```rust
  use vanilla::{JsonAsset, Timeline};
  
  let mut timeline_asset = JsonAsset::new();
  assert!(Timeline::create_from_json_asset(&mut timeline_asset).is_none());
  timeline_asset.load_from_bytes("intro.timeline.json", br#"{ "duration": 2, "loop": false }"#.to_vec());
  let timeline = Timeline::create_from_json_asset(&mut timeline_asset).expect("timeline");
  assert_eq!(timeline.get_duration(), 2.0);
  ```

- `pub fn set_description(&mut self, description: Value)` (method, since 0.3.2): Sets the description. (fills in missing stage / nodes / tracks / markers and marks it for recompilation)
  - `description` Value: New description JSON. If not an object, an empty description (create_empty_description) is used.
- `pub fn get_description(&self) -> &Value` (method, since 0.3.2): Returns the description.
  - returns &Value: Reference to the description JSON.
- `pub fn get_description_mut(&mut self) -> &mut Value` (method, since 0.3.2): Returns the description. (mutable. Call invalidate after editing tracks / keys)
  - returns &mut Value: Mutable reference to the description JSON.
- `pub fn invalidate(&mut self)` (method, since 0.3.2): Requests recompilation. (when tracks / keys change)
- `pub fn compile(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): Compiles. (sorts keys by time, attaches targets / property definitions, then gathers particles)
  - seek, tick and evaluate call it themselves if the description changed.
  - `node_tree` &mut NodeTree: Node tree holding the target nodes. (finds the particle systems of the target nodes)
- `pub fn collect_particle_systems(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): Gathers the particle systems of the target nodes.
  - Switches them to manual tick so they advance only by timeline time, and gives them a seed so rewinding always gives the same result.
  - `node_tree` &mut NodeTree: Node tree holding the target nodes. (looks only at nodes in the target table; keeps an existing seed, otherwise gives one in gathering order)
- `pub fn simulate_particles(&mut self, node_tree: &mut NodeTree, time_delta: f64)` (method, since 0.3.2): Advances particle time. (every frame during playback)
  - `node_tree` &mut NodeTree: Node tree holding the particle nodes.
  - `time_delta` f64: Time to advance. (seconds, does nothing if 0 or less)
- `pub fn resimulate_particles(&mut self, node_tree: &mut NodeTree, time: f64)` (method, since 0.3.2): Re-simulates particles. (scrubbing / rewinding. Clears them, then advances from 0 seconds while stepping through the events again)
  - One step is the larger of 1/60 second and time / 600. Particles with no event track count as started at 0 seconds.
  - `node_tree` &mut NodeTree: Node tree holding the particle nodes.
  - `time` f64: Timeline time to match. (seconds)
- `pub fn resolve_target(&self, target_name: &str) -> Option<TimelineTarget>` (method, since 0.3.2): Resolves a target. (target table → user resolver)
  - `target_name` &str: Track target name.
  - returns Option<TimelineTarget>: The entry in the target table if present, otherwise the target given by the resolver. None if neither.
- `pub fn set_target_resolver(&mut self, target_resolver: Option<TimelineTargetResolver>)` (method, since 0.3.2): Sets the target resolver. (name → target. Things that are not nodes are TimelineTarget::External(object))
  - `target_resolver` Option<TimelineTargetResolver>: Function that takes a name not in the target table and gives a target. (None for unknown names) None removes the resolver. Called during compilation.

  Example: Resolve the name "screen" to an External target

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{Timeline, TimelinePropertyTarget, TimelineTarget, TimelineValue};
  
  struct Silent;
  
  impl TimelinePropertyTarget for Silent {
  	fn set_timeline_property(&mut self, _property_name: &str, _value: &TimelineValue) {
  	}
  }
  
  let screen: Rc<RefCell<dyn TimelinePropertyTarget>> = Rc::new(RefCell::new(Silent));
  let mut timeline = Timeline::default();
  let resolved_screen = screen.clone();
  timeline.set_target_resolver(Some(Box::new(move |target_name: &str| {
  	if target_name == "screen" {
  		Some(TimelineTarget::External(resolved_screen.clone()))
  	}
  	else {
  		None
  	}
  })));
  assert_eq!(timeline.resolve_target("screen"), Some(TimelineTarget::External(screen)));
  assert_eq!(timeline.resolve_target("missing"), None);
  assert_eq!(timeline.get_target("screen"), None);
  ```

- `pub fn set_target(&mut self, target_name: &str, target: TimelineTarget)` (method, since 0.3.2): Registers a target directly. (replaces it if the same name exists)
  - `target_name` &str: Track target name.
  - `target` TimelineTarget: Target with that name. (a node handle or an External object)
- `pub fn get_target(&self, target_name: &str) -> Option<TimelineTarget>` (method, since 0.3.2): Returns a target. (only those in the target table)
  - `target_name` &str: Track target name.
  - returns Option<TimelineTarget>: Clone of the target registered in the target table. None if missing. (the resolver is not asked)
- `pub fn bind(&mut self, node_tree: &NodeTree, root_id: NodeId)` (method, since 0.3.2): Binds to a node tree by name. (when the stage was built manually. Searches the root itself or its descendants for track target names)
  - Names already in the target table are skipped, and names not found are not registered.
  - `node_tree` &NodeTree: Node tree to search for nodes.
  - `root_id` NodeId: Root node to start the search from.

  Example: Bind to an existing Hero node and apply a scale track

  ```rust
  use serde_json::json;
  use vanilla::{NodeTree, Timeline, TimelineTarget};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let world_id = node_tree.create_child(root_id, "World");
  let hero_id = node_tree.create_child(world_id, "Hero");
  let mut timeline = Timeline::new(Some(json!({
  	"duration": 1,
  	"tracks": [{ "target": "Hero", "property": "scaleX", "keys": [{ "time": 0, "value": 1 }, { "time": 1, "value": 3 }] }],
  })));
  timeline.bind(&node_tree, root_id);
  assert_eq!(timeline.get_target("Hero"), Some(TimelineTarget::Node(hero_id)));
  timeline.seek(&mut node_tree, 0.5);
  assert_eq!(node_tree[hero_id].get_local_scale().x, 2.0);
  ```

- `pub fn build_stage(&mut self, node_tree: &mut NodeTree, parent_id: NodeId, image_resolver: Option<TimelineImageResolver>) -> HashMap<String, NodeId>` (method, since 0.3.2): Creates the stage nodes. (builds the description's stage.nodes into the node tree and registers them as targets. Returns a name → node table)
  - `node_tree` &mut NodeTree: Node tree to create the nodes in.
  - `parent_id` NodeId: Stage parent node. (nodes whose parent is missing from the description, not found, itself or part of a cycle are attached here)
  - `image_resolver` Option<TimelineImageResolver>: Function that turns a sprite node's image name into an image. If None, only "data:" URL images are decoded.
  - returns HashMap<String, NodeId>: Node name → created node table. (the later one if two share a name)

  Example: Build a stage with parent relationships

  ```rust
  use serde_json::json;
  use vanilla::{NodeTree, Timeline, TimelineTarget};
  
  let mut timeline = Timeline::new(Some(json!({
  	"duration": 1,
  	"stage": { "nodes": [
  		{ "name": "Group", "type": "group", "x": 100 },
  		{ "name": "Box", "type": "paint", "parent": "Group" },
  	] },
  })));
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let node_table = timeline.build_stage(&mut node_tree, root_id, None);
  assert_eq!(node_tree.get_parent_id(node_table["Box"]), Some(node_table["Group"]));
  assert_eq!(node_tree.get_parent_id(node_table["Group"]), Some(root_id));
  assert_eq!(timeline.get_target("Box"), Some(TimelineTarget::Node(node_table["Box"])));
  ```

- `pub fn create_stage_node(node_tree: &mut NodeTree, node_description: &Value, image_resolver: Option<TimelineImageResolver>) -> NodeId` (static, since 0.3.2): Creates one stage node. (static. Creates a node that is not attached)
  - `node_tree` &mut NodeTree: Node tree to create the nodes in.
  - `node_description` &Value: Node object from the description's stage.nodes. (parent is ignored)
  - `image_resolver` Option<TimelineImageResolver>: Function that turns a sprite node's image name into an image. If None, only "data:" URL images are decoded.
  - returns NodeId: The created node. (not attached to any parent and not registered as a target)
- `pub fn apply_stage_node_description(node: &mut WorldNode, node_description: &Value, image_resolver: Option<TimelineImageResolver>)` (static, since 0.3.2): Applies a description to a node. (static. Also used when the editor changes values)
  - Applies the transform and visibility, attaches the component matching type if missing (Paint for paint, ShaderSprite and a grid for sprite, Text for text, ParticleSystem for particle, TimelineSound for sound), and applies the values.
  - `node` &mut WorldNode: Node to apply values to.
  - `node_description` &Value: Description node object. (missing entries come from TIMELINE_NODE_DEFAULTS)
  - `image_resolver` Option<TimelineImageResolver>: Function that turns a sprite node's image name into an image. If None, only "data:" URL images are decoded.
- `pub fn load_sounds(&mut self, node_tree: &mut NodeTree, engine: &Engine) -> Vec<Rc<AudioAsset>>` (method, since 0.3.2): Prepares sound nodes. (in place of the original setAudioManager + asset loading of sound nodes)
  - For each target node with a TimelineSound attached, loads any missing audio asset and creates a player. Returns the newly loaded assets.
  - `node_tree` &mut NodeTree: Node tree holding the sound nodes.
  - `engine` &Engine: Engine to load audio assets and create players with.
  - returns Vec<Rc<AudioAsset>>: List of audio assets newly loaded this time. (the scene may take them over with track_audio_asset; ones that failed to load are left out and the reason is printed to standard error)

  Example: Build the stage, then load the sounds and play them with event keys

  ```rust
  use serde_json::json;
  use vanilla::{Engine, EngineConfiguration, Scene, SceneBase, Timeline};
  
  struct SoundScene {
  	scene_base: SceneBase,
  	timeline: Timeline,
  }
  
  impl Scene for SoundScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn initialize(&mut self, engine: &Engine) {
  		self.timeline = Timeline::new(Some(json!({
  			"duration": 2,
  			"stage": { "nodes": [{ "name": "Hit", "type": "sound", "audio": "tests/assets/audio/wav_s16_stereo.wav" }] },
  			"tracks": [{ "target": "Hit", "property": "event", "keys": [{ "time": 0.5, "value": "play" }] }],
  		})));
  		let root_id = self.scene_base.get_root_id();
  		self.timeline.build_stage(self.scene_base.get_node_tree_mut(), root_id, None);
  		let audio_asset_list = self.timeline.load_sounds(self.scene_base.get_node_tree_mut(), engine);
  		for audio_asset in audio_asset_list.iter() {
  			self.scene_base.track_audio_asset(audio_asset);
  		}
  		self.timeline.play();
  	}
  
  	fn tick(&mut self, time_delta: f64) {
  		self.scene_base.tick(time_delta);
  		self.timeline.tick(self.scene_base.get_node_tree_mut(), time_delta);
  	}
  }
  
  let engine = Engine::new(EngineConfiguration::new());
  let sound_scene = SoundScene {
  	scene_base: SceneBase::new(),
  	timeline: Timeline::default(),
  };
  engine.run(Box::new(sound_scene)).unwrap();
  ```

- `pub fn stop_sound(node: &mut WorldNode)` (static, since 0.3.2): Stops a sound node. (static. Called by the editor on stop / rewind)
  - `node` &mut WorldNode: Node to stop. (does nothing if there is no TimelineSound or no player)
- `pub fn play(&mut self)` (method, since 0.3.2): Plays. (from the beginning if not looping and at the end)
- `pub fn pause(&mut self)` (method, since 0.3.2): Pauses.
- `pub fn stop(&mut self, node_tree: &mut NodeTree)` (method, since 0.3.2): Stops. (stops sounds and particles and goes back to the start)
  - `node_tree` &mut NodeTree: Node tree holding the target nodes. (applies the values at 0 seconds again)
- `pub fn seek(&mut self, node_tree: &mut NodeTree, time: f64)` (method, since 0.3.2): Moves in time. (no events fire. Particles advance again up to that time)
  - `node_tree` &mut NodeTree: Node tree holding the target nodes.
  - `time` f64: Time to move to. (seconds, clamped to 0 ~ duration)
- `pub fn tick(&mut self, node_tree: &mut NodeTree, time_delta: f64)` (method, since 0.3.2): Update. (advances time and applies values, firing events / markers passed)
  - Does nothing if not playing. If looping, wraps around when passing the end; otherwise stops at the end and calls the completion handler.
  - `node_tree` &mut NodeTree: Node tree holding the target nodes. (also passed to the handlers)
  - `time_delta` f64: Time elapsed since the last frame. (seconds, advanced after multiplying by the speed)
- `pub fn fire_events_between(&mut self, node_tree: &mut NodeTree, from_time: f64, to_time: f64)` (method, since 0.3.2): Fires event keys / markers in a range. (greater than from_time up to and including to_time. Event tracks in order, then markers)
  - `node_tree` &mut NodeTree: Node tree holding the target nodes. (particle and sound nodes receive the events, and it is also passed to the handlers)
  - `from_time` f64: Start of the range. (seconds, keys at this time are excluded. Pass a negative value to include keys at 0 seconds)
  - `to_time` f64: End of the range. (seconds, keys at this time are included)
- `pub fn evaluate(&mut self, node_tree: &mut NodeTree, time: f64)` (method, since 0.3.2): Applies the values at a time. (continuous properties only; events fire only in tick. For External targets, passes them with set_timeline_property and records the applied values)
  - Disabled tracks, tracks with no keys and tracks whose target is not found are skipped. The time is not clamped.
  - `node_tree` &mut NodeTree: Node tree holding the target nodes.
  - `time` f64: Time to sample. (seconds)
- `pub fn get_external_properties(&self) -> &[TimelineExternalProperty]` (method, since 0.3.2): Returns the values the last evaluate applied to External targets. (in track order)
  - returns &[TimelineExternalProperty]: Slice of values applied to External targets. (empty before evaluate)
- `pub fn sample_keys(sorted_keys: &[TimelineKey], kind: TimelinePropertyKind, time: f64) -> TimelineValue` (static, since 0.3.2): Samples the value at a time from a key list. (static. Keys must be in time order. Also used by the editor's curve drawing)
  - `sorted_keys` &[TimelineKey]: Key list sorted by time.
  - `kind` TimelinePropertyKind: Value kind. (Number and Color interpolate with the previous key's easing; others take the previous key's value)
  - `time` f64: Time to sample. (seconds; before the first key it is the first key's value, after the last key the last key's value)
  - returns TimelineValue: The value at that time. With no keys, Number(0) for Number, None otherwise.
- `pub fn sample_track(track: &Value, time: f64) -> TimelineValue` (static, since 0.3.2): Samples a description track's value at a time. (static. The description track as is, sorted here. Properties with no definition are number)
  - `track` &Value: Description track object. ({ property, keys })
  - `time` f64: Time to sample. (seconds)
  - returns TimelineValue: The value at that time. (same as sample_keys)

  Example: Sample a color track and a text track

  ```rust
  use serde_json::json;
  use vanilla::{Timeline, TimelineValue};
  
  let color_track = json!({ "property": "color", "keys": [{ "time": 0, "value": "#ff0000ff" }, { "time": 2, "value": "#0000ffff" }] });
  assert_eq!(Timeline::sample_track(&color_track, 1.0), TimelineValue::String(String::from("#800080ff")));
  let text_track = json!({ "property": "text", "keys": [{ "time": 1, "value": "B" }, { "time": 0, "value": "A" }] });
  assert_eq!(Timeline::sample_track(&text_track, 0.5).to_text(), "A");
  assert_eq!(Timeline::sample_track(&text_track, 1.0).to_text(), "B");
  ```

- `pub fn get_time(&self) -> f64` (method, since 0.3.2): Returns the time.
  - returns f64: Current playback time. (seconds, 0 ~ duration)
- `pub fn is_playing(&self) -> bool` (method, since 0.3.2): Returns whether it is playing.
  - returns bool: true after play and before pause, stop or reaching the end.
- `pub fn set_speed(&mut self, speed: f64)` (method, since 0.3.2): Sets the speed. (1 = real time)
  - `speed` f64: Time scale. (2 is double speed; if negative it runs backward, does not go past 0, and no events fire)
- `pub fn get_speed(&self) -> f64` (method, since 0.3.2): Returns the speed.
  - returns f64: Time scale. (default 1)
- `pub fn set_loop(&mut self, is_loop: bool)` (method, since 0.3.2): Sets looping. (changes the description's loop)
  - `is_loop` bool: Whether to wrap around to the start when passing the end.
- `pub fn is_loop(&self) -> bool` (method, since 0.3.2): Returns whether it loops. (only when the description's loop is true)
  - returns bool: true if the description's loop is the boolean true. (false if missing or another type)
- `pub fn get_duration(&self) -> f64` (method, since 0.3.2): Returns the duration. (seconds, 0 if unreadable or 0 or less)
  - returns f64: The description's duration. (seconds, also accepts strings that read as numbers like "4". 0 if unreadable or 0 or less)
- `pub fn get_frame_rate(&self) -> f64` (method, since 0.3.2): Returns the frames per second. (30 if unreadable or 0 or less)
  - returns f64: frameRate of the description. (30 if it cannot be read or is 0 or less, not used to compute the playback time)
- `pub fn set_event_handler(&mut self, event_handler: Option<TimelineEventHandler>)` (method, since 0.3.2): Sets the event handler. ((target name, event name, key, timeline, node tree))
  - `event_handler` Option<TimelineEventHandler>: Function called for each event track key tick passes. (the event name is the key value's string; also called for tracks whose target is not found) None removes it.

  Example: Record events and stop at land

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use serde_json::json;
  use vanilla::{NodeTree, Timeline, TimelineKey};
  
  let event_list: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
  let mut node_tree = NodeTree::new();
  let mut timeline = Timeline::new(Some(json!({
  	"duration": 2,
  	"loop": true,
  	"tracks": [{ "target": "hero", "property": "event", "keys": [{ "time": 0.5, "value": "jump" }, { "time": 1.5, "value": "land" }] }],
  })));
  let recorded_list = event_list.clone();
  timeline.set_event_handler(Some(Box::new(move |target_name: &str, event_name: &str, key: &TimelineKey, timeline: &mut Timeline, _node_tree: &mut NodeTree| {
  	recorded_list.borrow_mut().push(format!("{} {} {}", target_name, event_name, key.time));
  	if event_name == "land" {
  		timeline.pause();
  	}
  })));
  timeline.play();
  timeline.tick(&mut node_tree, 1.0);
  timeline.tick(&mut node_tree, 1.0);
  assert_eq!(*event_list.borrow(), vec![String::from("hero jump 0.5"), String::from("hero land 1.5")]);
  assert!(!timeline.is_playing());
  ```

- `pub fn set_marker_handler(&mut self, marker_handler: Option<TimelineMarkerHandler>)` (method, since 0.3.2): Sets the marker handler. ((marker name, marker, timeline, node tree))
  - `marker_handler` Option<TimelineMarkerHandler>: Function called for each marker tick passes. (in time order after the event keys of that range) None removes it.
- `pub fn set_complete_handler(&mut self, complete_handler: Option<TimelineCompleteHandler>)` (method, since 0.3.2): Sets the completion handler. (when reaching the end while not looping, (timeline, node tree))
  - `complete_handler` Option<TimelineCompleteHandler>: Function called once on the tick where non-looping playback reaches the end. (after applying the end values) None removes it.

  Example: Count when a 1-second timeline ends

  ```rust
  use std::cell::Cell;
  use std::rc::Rc;
  use serde_json::json;
  use vanilla::{NodeTree, Timeline};
  
  let completed_count = Rc::new(Cell::new(0));
  let mut node_tree = NodeTree::new();
  let mut timeline = Timeline::new(Some(json!({ "duration": 1, "loop": false })));
  let counter = completed_count.clone();
  timeline.set_complete_handler(Some(Box::new(move |_timeline: &mut Timeline, _node_tree: &mut NodeTree| {
  	counter.set(counter.get() + 1);
  })));
  timeline.play();
  timeline.tick(&mut node_tree, 0.6);
  timeline.tick(&mut node_tree, 0.6);
  assert_eq!(completed_count.get(), 1);
  assert_eq!(timeline.get_time(), 1.0);
  ```

## Functions and constants

- `pub const TIMELINE_EASING_NAMES: [&str; 33]` (field, since 0.3.2): Easing name list. ("linear" / "step" / "bezier" / "<family>.<in|out|inOut>")
  - returns [&str; 33]
- `pub fn create_bezier_easing(x1: f64, y1: f64, x2: f64, y2: f64) -> impl Fn(f64) -> f64 + Clone` (method, since 0.3.2): Creates a cubic Bezier easing. (same control points as CSS cubic-bezier, x is 0 ~ 1)
  - `x1` f64: x of the first control point. (clamped to 0 ~ 1)
  - `y1` f64: y of the first control point. (not clamped; outside 0 ~ 1 it overshoots and comes back)
  - `x2` f64: x of the second control point. (clamped to 0 ~ 1)
  - `y2` f64: y of the second control point. (not clamped)
  - returns impl Fn(f64) -> f64 + Clone: Function that takes progress (0 ~ 1) and produces the eased value. (progress 0 or less is 0, 1 or more is 1)

  Example: CSS ease-in-out curve

  ```rust
  use vanilla::create_bezier_easing;
  
  let ease_in_out = create_bezier_easing(0.42, 0.0, 0.58, 1.0);
  assert_eq!(ease_in_out(0.0), 0.0);
  assert_eq!(ease_in_out(1.0), 1.0);
  assert!((ease_in_out(0.5) - 0.5).abs() < 0.001);
  assert!(ease_in_out(0.1) < 0.1);
  ```

- `pub fn resolve_timeline_easing(easing_name: &str, curve: Option<&[f64]>) -> TimelineEasing` (method, since 0.3.2): Returns an easing. (unknown names are linear; "bezier" uses curve [x1, y1, x2, y2], ease-in-out if missing)
  - `easing_name` &str: Easing name. (one of TIMELINE_EASING_NAMES, an empty string is linear)
  - `curve` Option<&[f64]>: Control points [x1, y1, x2, y2] for "bezier". If missing or fewer than four, [0.42, 0, 0.58, 1]. Ignored if not "bezier".
  - returns TimelineEasing: Easing value called with evaluate(progress).

  Example: Pick an easing by name

  ```rust
  use vanilla::resolve_timeline_easing;
  
  let quadratic_in = resolve_timeline_easing("quadratic.in", None);
  assert_eq!(quadratic_in.evaluate(0.5), 0.25);
  let step = resolve_timeline_easing("step", None);
  assert_eq!(step.evaluate(0.9), 0.0);
  let curve: [f64; 4] = [0.68, -0.55, 0.265, 1.55];
  let overshoot = resolve_timeline_easing("bezier", Some(&curve));
  assert!(overshoot.evaluate(0.3) < 0.0);
  assert_eq!(resolve_timeline_easing("unknown", None).evaluate(0.3), 0.3);
  ```

- `pub fn parse_timeline_color(hex_text: &str) -> [f64; 4]` (method, since 0.3.2): Color string → channels. ("#rrggbb" or "#rrggbbaa", unreadable channels are 1)
  - `hex_text` &str: Color string. If it does not start with "#", it reads as white. Each channel reads two characters, taking only the leading hex digits like the original parseInt(string, 16).
  - returns [f64; 4]: [red, green, blue, alpha] channels. (0 ~ 1, alpha is read only with eight characters, otherwise 1)

  Example: Read a color string

  ```rust
  use vanilla::parse_timeline_color;
  
  assert_eq!(parse_timeline_color("#ff000080"), [1.0, 0.0, 0.0, 128.0 / 255.0]);
  assert_eq!(parse_timeline_color("#00ff00"), [0.0, 1.0, 0.0, 1.0]);
  assert_eq!(parse_timeline_color("red"), [1.0, 1.0, 1.0, 1.0]);
  ```

- `pub fn compose_timeline_color(channels: &[f64]) -> String` (method, since 0.3.2): Channels → color string. ("#rrggbbaa", 1 if alpha is missing)
  - `channels` &[f64]: [red, green, blue, alpha] channels. (clamped to 0 ~ 1 and rounded; missing red, green and blue are 0)
  - returns String: Lowercase "#rrggbbaa" string.

  Example: Channels to a color string

  ```rust
  use vanilla::compose_timeline_color;
  
  assert_eq!(compose_timeline_color(&[1.0, 0.5, 0.0, 1.0]), "#ff8000ff");
  assert_eq!(compose_timeline_color(&[0.2, 0.4, 0.6]), "#336699ff");
  ```

- `pub const TIMELINE_PROPERTY_DEFINITIONS: [TimelinePropertyDefinition; 17]` (field, since 0.3.2): List of animation property definitions. (in the declaration order of the original TIMELINE_PROPERTY_DEFINITIONS)
  - returns [TimelinePropertyDefinition; 17]
- `pub fn find_timeline_property_definition(property_name: &str) -> Option<&'static TimelinePropertyDefinition>` (method, since 0.3.2): Finds a property definition. (the original `TIMELINE_PROPERTY_DEFINITIONS[name]`)
  - `property_name` &str: Property name. (case-sensitive)
  - returns Option<&'static TimelinePropertyDefinition>: The definition with that name. None if missing.
- `pub static TIMELINE_NODE_DEFAULTS: LazyLock<TimelineNodeDescription> = LazyLock::new(TimelineNodeDescription::default)` (field, since 0.3.2): Description node defaults. (the original TIMELINE_NODE_DEFAULTS)
  - returns LazyLock<TimelineNodeDescription>

## TimelineEasing (enum) (Clone, Copy, Debug)

Timeline easing. (in place of the function resolve_timeline_easing returns in the original)

- `Function` = `Function(EasingFunction)`: Tween easing function, linear, step.
- `Bezier` = `Bezier(f64, f64, f64, f64)`: Cubic Bezier (x1, y1, x2, y2).

- `pub fn evaluate(&self, progress: f64) -> f64` (method, since 0.3.2): Eased value of progress (0 ~ 1).
  - `progress` f64: Span progress. (0 ~ 1)
  - returns f64: Eased value. (usually 0 ~ 1; overshooting curves like elastic, back and Bezier y go outside. step is always 0)

## TimelineValue (enum) (Clone, Debug, PartialEq)

Timeline value. (the original key values: number, string, boolean)

- `None`: No value. (the original null)
- `Number` = `Number(f64)`: Number.
- `String` = `String(String)`: String. (colors "#rrggbbaa" and event names are this too)
- `Boolean` = `Boolean(bool)`: Boolean.

- `pub fn from_json(value: &Value) -> TimelineValue` (static, since 0.3.2): Creates from a JSON value. (arrays and objects are none)
  - `value` &Value: The value field of a description key.
  - returns TimelineValue: Numbers are Number(f64), strings String, booleans Boolean; null, arrays and objects are None.

  Example: JSON value to a timeline value

  ```rust
  use serde_json::json;
  use vanilla::TimelineValue;
  
  assert_eq!(TimelineValue::from_json(&json!(2.5)), TimelineValue::Number(2.5));
  assert_eq!(TimelineValue::from_json(&json!("hit")), TimelineValue::String(String::from("hit")));
  assert_eq!(TimelineValue::from_json(&json!([1, 2])), TimelineValue::None);
  ```

- `pub fn to_json(&self) -> Value` (method, since 0.3.2): Converts to a JSON value.
  - returns Value: None is null, numbers are JSON numbers (NaN and infinity are null), strings and booleans as is.
- `pub fn as_number(&self) -> f64` (method, since 0.3.2): Reads as a number. (the original Number(value). Strings are parsed, booleans are 1 / 0, none is 0)
  - returns f64: Number. Strings are parsed after trimming leading and trailing whitespace. (an empty string is 0, NaN if unreadable)

  Example: Several values as numbers

  ```rust
  use vanilla::TimelineValue;
  
  assert_eq!(TimelineValue::String(String::from(" 12.5 ")).as_number(), 12.5);
  assert_eq!(TimelineValue::Boolean(true).as_number(), 1.0);
  assert_eq!(TimelineValue::None.as_number(), 0.0);
  assert!(TimelineValue::String(String::from("abc")).as_number().is_nan());
  ```

- `pub fn to_text(&self) -> String` (method, since 0.3.2): Reads as a string. (the original String(value))
  - returns String: String. None is "null", numbers without a decimal point if integral (-0 is "0", infinity is "Infinity" / "-Infinity"), booleans are "true" / "false".

  Example: Value as a string

  ```rust
  use vanilla::TimelineValue;
  
  assert_eq!(TimelineValue::Number(3.0).to_text(), "3");
  assert_eq!(TimelineValue::Number(0.5).to_text(), "0.5");
  assert_eq!(TimelineValue::None.to_text(), "null");
  assert_eq!(TimelineValue::Boolean(false).to_text(), "false");
  ```

- `pub fn is_true(&self) -> bool` (method, since 0.3.2): Whether to treat it as true. (the original visible property: true or "true")
  - returns bool: true if Boolean(true) or the string "true". Numbers and None are false.

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

Property kind. (number interpolates with easing, color interpolates channels, string / boolean are stepped)

- `Number`: Number. (interpolated between keys with easing)
- `Color`: Color string. (each channel interpolated with easing)
- `String`: String. (stepped, changes at the next key)
- `Boolean`: Boolean. (stepped)

## TimelineTarget (enum) (Clone, PartialEq, std::fmt::Debug)

Track target. (a node, or something that is not a node)

- `Node` = `Node(NodeId)`: Node. (defined properties are applied directly to the node)
- `External` = `External(Rc<RefCell<dyn TimelinePropertyTarget>>)`: Something that is not a node. (an object with the original setTimelineProperty; evaluate passes values to it right there)
