# animation/timeline (vanilla.js 0.4.0)

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

Timeline.

## Timeline extends Object

Timeline.
- The document (description) is JSON made of a stage node list + tracks (target name / property / keys) + markers, and the timeline editor saves it.
- Create the stage nodes with buildStage(), or attach by name to an existing node tree with bind().
- A key's easing applies to the segment from that key to the next key.
- Usage:
    const timeline = await Timeline.loadFromUrl("./assets/intro.timeline.json");
    timeline.buildStage(stageNode, (imageName) => imageTable[imageName]);
    timeline.play();
    // every frame: timeline.tick(timeDelta);

Example: Load a document, build the stage and play

```js
import { Engine, EngineConfiguration, Scene, Timeline, Vector2 } from "./build/vanilla.js";

const emblemImage = new Image();
emblemImage.src = "examples/timelineshowcase/assets/emblem.png";
await emblemImage.decode();
const timeline = await Timeline.loadFromUrl("examples/timelineshowcase/assets/logo.timeline.json");
timeline.setMarkerHandler((markerName) => {
	console.log("marker", markerName);
});

class TimelineScene extends Scene {
	async load(engine) {
		await super.load(engine);
		const root = this.getRoot();
		timeline.buildStage(root, (imageName) => {
			return imageName === "emblem.png" ? emblemImage : null;
		});
		timeline.play();
	}

	tick(timeDelta) {
		super.tick(timeDelta);
		timeline.tick(timeDelta);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(960, 540);
const engine = new Engine(engineConfiguration);
engine.run(new TimelineScene());
```

- `constructor(description = null)` (constructor, since 0.3.0): Constructor.
  - `description` object | null: Timeline document. (the empty document from createEmptyDescription if null)
- `static createEmptyDescription()` (static, since 0.3.0): Creates an empty description. (static)
  - returns object: An empty timeline document. (3 seconds, 30 frames, looping, 960x540 stage)
- `static async loadFromUrl(url)` (static, since 0.3.0): Loads from a URL. (static)
  - `url` string: URL of the timeline document (*.timeline.json).
  - returns Promise<Timeline>: Timeline made from the loaded document. (Rejected for a failed response (404 and so on) or non-JSON)
- `static loadFromText(text)` (static, since 0.4.0): Creates from JSON text. (static)
  - `text` string: Timeline document JSON text.
  - returns Timeline: The created timeline.
- `static createFromJsonAsset(jsonAsset)` (static, since 0.4.0): Creates from a loaded JsonAsset. (static, null if not loaded yet or failed. The document is copied)
  - `jsonAsset` JsonAsset: JsonAsset that loaded a timeline document.
  - returns Timeline | null: The created timeline. null if not loaded yet or failed.

  Example: Create from a document loaded as a JsonAsset

  ```js
  import { JsonAsset, Timeline } from "./build/vanilla.js";
  
  const jsonAsset = new JsonAsset();
  await jsonAsset.load("examples/timelineshowcase/assets/title.timeline.json");
  const timeline = Timeline.createFromJsonAsset(jsonAsset);
  console.log(timeline.getDuration(), timeline.getFrameRate(), timeline.isLoop());
  ```

- `setDescription(description)` (method, since 0.3.0): Sets the description. (uses the reference as is, after the editor changes it, recompile with invalidate())
  - `description` object: Timeline document. (missing stage, tracks and markers are filled in)
- `getDescription()` (method, since 0.3.0): Returns the description.
  - returns object: Timeline document. (not a copy)
- `invalidate()` (method, since 0.3.0): Requests recompilation. (when tracks / keys change)
- `compile()` (method, since 0.3.0): Compile. (sorts keys by time and attaches target / property definitions)
- `collectParticleSystems()` (method, since 0.3.0): Collects the particle systems of target nodes. (switches them to manual tick so they advance only on timeline time, and gives them a seed so every rewind gives the same result)
- `simulateParticles(timeDelta)` (method, since 0.3.0): Advances particle time. (every frame during playback)
  - `timeDelta` number: Time to advance. (seconds, does nothing if 0 or less)
- `resimulateParticles(time)` (method, since 0.3.0): Re-simulates particles. (scrub / rewind, clears them and advances from 0 seconds, stepping through the events again)
  - `time` number: Timeline time to match. (seconds)
- `resolveTarget(targetName)` (method, since 0.3.0): Resolves a target. (stage node table → user resolver)
  - `targetName` string: Target name of the track.
  - returns object | null: The found target. null if none.
- `setTargetResolver(targetResolver)` (method, since 0.3.0): Sets the target resolver. (name → object. It need not be a node, as long as it has setTimelineProperty(name, value))
  - `targetResolver` Function | null: Function that takes a target name and returns an object. (off if null)
- `setTarget(targetName, target)` (method, since 0.3.0): Registers a target directly.
  - `targetName` string: Target name of the track.
  - `target` object: A node, or an object with setTimelineProperty(name, value).

  Example: Drive a non-node object with a track

  ```js
  import { Timeline } from "./build/vanilla.js";
  
  const description = Timeline.createEmptyDescription();
  description.duration = 2;
  description.loop = false;
  description.tracks.push({
  	target: "meter",
  	property: "level",
  	keys: [
  		{ time: 0, value: 0, easing: "quadratic.out" },
  		{ time: 2, value: 100 }
  	]
  });
  const timeline = new Timeline(description);
  const meter = { level: 0 };
  meter.setTimelineProperty = (name, value) => {
  	meter[name] = value;
  };
  timeline.setTarget("meter", meter);
  timeline.seek(1);
  console.log(timeline.getTime(), meter.level);
  ```

- `getTarget(targetName)` (method, since 0.3.0): Returns a target.
  - `targetName` string: Target name of the track.
  - returns object | null: The registered target. null if none. (does not consult the resolver)
- `bind(rootNode)` (method, since 0.3.0): Attaches by name to a node tree. (when the stage was built manually)
  - `rootNode` WorldNode: Root of the node tree to search by name. (the root itself is checked too. Names already registered are skipped)
- `buildStage(parentNode, imageResolver = null)` (method, since 0.3.0): Creates the stage nodes. (builds the description's stage.nodes into a node tree and registers them as targets)
  - If two nodes share a name, both are attached, and the latter remains in the name table.
  - If the parent is itself or forms a cycle, it is attached to parentNode.
  - `parentNode` WorldNode: Parent node for the stage nodes. (nodes without a parent in the description are attached here)
  - `imageResolver` Function | null: (image name) → HTMLImageElement | HTMLCanvasElement | null
  - returns System.Map: name → node
- `static isAncestorOrSelf(ancestorNode, node)` (static, since 0.4.0): Whether ancestorNode is node itself or one of its ancestors. (static)
  - `ancestorNode` WorldNode: Node to test as an ancestor.
  - `node` WorldNode: Node to walk up the parents from.
  - returns boolean: True if ancestorNode is node itself or one of its ancestors.
- `static createStageNode(nodeDescription, imageResolver = null)` (static, since 0.3.0): Creates a single stage node. (static)
  - `nodeDescription` object: Stage node description. (missing values are filled from TIMELINE_NODE_DEFAULTS)
  - `imageResolver` Function | null: Function that takes an image name and returns an image. (if missing or it returns null, only data: URLs are read on its own)
  - returns WorldNode: A new node named after the description.
- `static applyStageNodeDescription(node, nodeDescription, imageResolver = null)` (static, since 0.3.0): Applies the description to a node. (static, also used when the editor changes values)
  - `node` WorldNode: Node to apply the description to. (adds the component for the type if missing)
  - `nodeDescription` object: Stage node description. (missing values are filled from TIMELINE_NODE_DEFAULTS)
  - `imageResolver` Function | null: Function that takes an image name and returns an image. (if missing or it returns null, only data: URLs are read on its own)
- `static setAudioManager(audioManager)` (static, since 0.3.0): Sets the audio manager. (static, used when sound nodes create players)
  - `audioManager` object | null: Audio manager that sound nodes use to create players with createAudioPlayer. (none are created if null)
- `static stopSound(node)` (static, since 0.3.0): Stops sound nodes. (static, called by the editor on stop / rewind)
  - `node` WorldNode: Sound node to stop. (does nothing if it is not a sound node)
- `play()` (method, since 0.3.0): Play.
- `pause()` (method, since 0.3.0): Pauses.
- `stop()` (method, since 0.3.0): Stop. (back to the start)
- `seek(time)` (method, since 0.3.0): Moves to a time. (events are not fired)
  - `time` number: Time to move to. (seconds, clamped to 0 ~ duration)
- `tick(timeDelta)` (method, since 0.3.0): Update. (advances time and applies values, fires passed events / markers)
  - `timeDelta` number: Time since the last frame. (seconds, multiplied by the speed. Does nothing unless playing)

  Example: Receive events, markers and completion while playing

  ```js
  import { Timeline } from "./build/vanilla.js";
  
  const description = Timeline.createEmptyDescription();
  description.duration = 1;
  description.loop = false;
  description.tracks.push({
  	target: "hero",
  	property: "event",
  	keys: [
  		{ time: 0.5, value: "jump" }
  	]
  });
  description.markers.push({ time: 0.25, name: "quarter" });
  const timeline = new Timeline(description);
  timeline.setEventHandler((targetName, eventName) => {
  	console.log("event", targetName, eventName);
  });
  timeline.setMarkerHandler((markerName) => {
  	console.log("marker", markerName);
  });
  timeline.setCompleteHandler(() => {
  	console.log("complete", timeline.getTime());
  });
  timeline.play();
  for (let frame = 0; frame < 40; ++frame) {
  	timeline.tick(1 / 30);
  }
  ```

- `fireEventsBetween(fromTime, toTime)` (method, since 0.3.0): Fires event keys / markers within the interval. (greater than fromTime ~ up to toTime)
  - `fromTime` number: Start of the range. (seconds, keys at this time are excluded)
  - `toTime` number: End of the range. (seconds, keys at this time are included)
- `dispatchEvent(compiledTrack, key, isSilent = false)` (method, since 0.3.0): Handles an event key. (particle targets handle play / stop / emit:N themselves, others go to the handler)
  - `compiledTrack` object: Compiled event track. (uses target and track)
  - `key` object: Event key. (value is the event name)
  - `isSilent` boolean: For re-simulation. (does not call sound / user handlers, particles only)
- `evaluate(time)` (method, since 0.3.0): Applies the values at a time. (continuous properties only, events fire only in tick)
  - `time` number: Time whose values are applied. (seconds)
- `static sampleKeys(sortedKeys, kind, time)` (static, since 0.3.0): Samples the value at a time from a key list. (static, also used for the editor's curve drawing)
  - `sortedKeys` object[]: Key list sorted by time. ({ time, value, easing, curve })
  - `kind` string: One of "number", "color", "string", "boolean". (only number and color interpolate, the rest step)
  - `time` number: Sample time. (seconds)
  - returns *: Value at that time. (0 for number and null for the rest if there are no keys)
- `static sampleTrack(track, time)` (static, since 0.3.0): Samples a track's value at a time. (the description track as is, sorting is done here)
  - `track` object: A track from the description. (property decides the kind, unknown properties are number)
  - `time` number: Sample time. (seconds)
  - returns *: Value at that time.
- `getTime()` (method, since 0.3.0): Returns the time.
  - returns number: Current time. (seconds)
- `isPlaying()` (method, since 0.3.0): Returns whether it is playing.
  - returns boolean: True if playing.
- `setSpeed(speed)` (method, since 0.3.0): Sets the speed. (1 = real time)
  - `speed` number: Playback speed factor. (1 = real time, negative values stop at 0 seconds)
- `getSpeed()` (method, since 0.3.0): Returns the speed.
  - returns number: Playback speed factor.
- `setLoop(isLoop)` (method, since 0.3.0): Sets looping.
  - `isLoop` boolean: True to loop. (written to the document's loop)
- `isLoop()` (method, since 0.3.0): Returns whether it loops.
  - returns boolean: True if the document's loop is true.
- `getDuration()` (method, since 0.3.0): Returns the duration. (seconds)
  - returns number: Duration. (seconds, 0 if the document value is not positive)
- `getFrameRate()` (method, since 0.3.0): Returns the frames per second.
  - returns number: Frames per second. (30 if the document value is not positive)
- `setEventHandler(eventHandler)` (method, since 0.3.0): Sets the event handler. ((target name, event name, key, timeline))
  - `eventHandler` Function | null: Function that receives (target name, event name, key, timeline). (off if null)
- `setMarkerHandler(markerHandler)` (method, since 0.3.0): Sets the marker handler. ((marker name, marker, timeline))
  - `markerHandler` Function | null: Function that receives (marker name, marker, timeline). (off if null)
- `setCompleteHandler(completeHandler)` (method, since 0.3.0): Sets the completion handler. (when reaching the end while not looping)
  - `completeHandler` Function | null: Function that receives the timeline. (off if null)

## Functions and constants

- `TIMELINE_EASING_NAMES` (field, since 0.3.0): Easing name list. ("linear" / "step" / "bezier" / "<family>.<in|out|inOut>")
- `createBezierEasing(x1, y1, x2, y2)` (method, since 0.3.0): Creates a cubic Bezier easing. (same control points as CSS cubic-bezier, x is 0 ~ 1)
  - `x1` number: x of the first control point. (clamped to 0 ~ 1)
  - `y1` number: y of the first control point.
  - `x2` number: x of the second control point. (clamped to 0 ~ 1)
  - `y2` number: y of the second control point.
  - returns Function: Function that takes 0 ~ 1 progress and returns the eased value.
- `resolveTimelineEasing(easingName, curve = null)` (method, since 0.3.0): Returns an easing function. (unknown names give linear, "bezier" uses curve [x1, y1, x2, y2])
  - `easingName` string: Easing name. (one of TIMELINE_EASING_NAMES, linear if empty)
  - `curve` number[] | null: [x1, y1, x2, y2] for "bezier". ([0.42, 0, 0.58, 1] if fewer than four)
  - returns Function: Function that takes 0 ~ 1 progress and returns the eased value.

  Example: Get easings by name and by control points

  ```js
  import { resolveTimelineEasing, createBezierEasing } from "./build/vanilla.js";
  
  const bounceOut = resolveTimelineEasing("bounce.out");
  const customCurve = resolveTimelineEasing("bezier", [0.25, 0.1, 0.25, 1]);
  const easeInOut = createBezierEasing(0.42, 0, 0.58, 1);
  console.log(bounceOut(0.5), customCurve(0.5), easeInOut(0.25));
  ```

- `parseTimelineColor(hexText)` (method, since 0.3.0): Color string ↔ channels.
  - `hexText` string: "#rrggbb" or "#rrggbbaa"
  - returns number[]: [red, green, blue, alpha] in 0 ~ 1. (1 for channels that cannot be read)
- `composeTimelineColor(channels)` (method, since 0.3.0): Channels to a color string. ("#rrggbbaa")
  - `channels` number[]: [red, green, blue, alpha] in 0 ~ 1. (clamped to 0 ~ 1, alpha is 1 if missing)
  - returns string: "#rrggbbaa" color string.
- `TIMELINE_PROPERTY_DEFINITIONS` (field, since 0.3.0): Animated property definitions. (name → kind / apply function)
  - kind: "number" uses easing interpolation, "color" uses channel interpolation, "string" / "boolean" step.
- `TIMELINE_NODE_DEFAULTS` (field, since 0.3.0): Description node defaults.
