## Expressions

Write an expression when the caller asks for one, or when procedural motion such as oscillation, wiggle, looping or a layer dependency fits the result. It is a script string `x` inside one of these transform properties:

| Property | Notes |
| --- | --- |
| `ks.p` | Position |
| `ks.p.x`, `ks.p.y` | Separated position: each axis is a property object, and its own `x` member holds the script |
| `ks.a`, `ks.s` | Anchor, scale |
| `ks.r` | Rotation. Not run on a layer with `rx`. |
| `ks.o` | Opacity. Not run on a null, a camera or a collapsed precomposition. |

Expressions don't run on `rx`, `ry`, `rz` or `or`. On a layer with `rx`, no rotation expression runs, `r` included.

This adds a 30-pixel vertical oscillation with a two-second period to a position, and keeps its base:

```json
{"a":0,"k":[944,204,0],"x":"[value[0], value[1] + 30 * Math.sin(2 * Math.PI * time / 2), value[2]];"}
```

- Preserve the property's `a`, `k` and other metadata: they give its static or keyframed base and its fallback. Don't switch a static property to `a:1` because its expression changes over time.
- An expression can override the base, so changing only `k` may change nothing.

### How to write a script

Expressions follow an After Effects-style model: JavaScript computes the value from inputs such as `time` and `value`. Only what this section describes is supported. Don't assume full After Effects compatibility.

- End with the expression whose value is assigned. Don't use a top-level `return`. In longer scripts, use `var` for temporaries and finish with a number or list.
- The final value must be a number or a list. Anything else is converted the way JavaScript's `Number()` converts it, not replaced by the authored value: `true` becomes 1, `false` and `null` become 0, and a string that reads as a number becomes that number. Other strings, objects and `undefined` become NaN. That includes `undefined` from a script ending in a `var` declaration or an `if` without a value.
- Return a number for rotation, opacity or a separated axis, and an explicit three-component list for position, anchor or scale. Keep results finite.
- `time` is in seconds. `value` is the authored property at the current time, before this expression: add offsets to it to keep existing animation.
- Units: position and anchor in pixels, rotation in degrees, scale and opacity in percent (100 is full). Preserve Z when you change only X and Y.
- Use component-wise arithmetic. Expressions are supported as Bodymovin exports them: hand-written `+`, `-` or `*` directly on arrays is outside the supported path.

All expressions share one script context and run again every frame. They run on every layer of an active composition, hidden layers and layers outside their `ip` and `op` included. Expression selectors run once for each character, word or line their `b` counts.

- A top-level `let`, `const` or `class` fails from the second run, and the expression falls back to the property's value. Another expression declaring the same top-level name fails from its first run. `warnings` flag each expression with a top-level `let`, `const` or `class`. Declarations inside a function or block are fine.
- Top-level `var` and function names are shared too, and the helpers are ordinary globals. Never name a top-level variable or function after a helper or global such as `ease`, `linear`, `clamp`, `smooth`, `wiggle`, `key`, `loopOut` or `thisComp`. It would replace it for every other expression.
- Top-level `var` values persist from frame to frame. Don't rely on them: compute each frame's value from its inputs.
- All scripts together get 64 MB of memory and a 256 KB stack. A script that exceeds either throws and falls back.

| Intent | Property | Script |
| --- | --- | --- |
| Gentle rotation around the authored angle | `ks.r` | `value + 8 * Math.sin(2 * Math.PI * time / 2);` |
| Pulse X and Y scale by 5%, keep Z | `ks.s` | `var factor = 1 + 0.05 * Math.sin(2 * Math.PI * time / 2); [value[0] * factor, value[1] * factor, value[2]];` |
| Position wiggle around existing motion | `ks.p` | `wiggle(2, 15);` |
| Repeat a keyframed track after its last key | A supported keyframed property | `loopOut("cycle");` |
| Ping-pong a keyframed track | A supported keyframed property | `loopOut("pingpong");` |
| Offset separated X by 40 pixels | `ks.p.x` | `value + 40;` |

### What does not run

- Expressions on other shape, effect or text-document properties don't run. An `x` on an effect parameter's `v` or a layer-style property is ignored: the value renders without it, with a warning.
- This is not the whole After Effects host API: no file system, network or host access.
- An expression that throws, or names a missing layer, falls back to the authored value. A successful save or render does not prove it ran.
- A script that runs too long on one frame, such as an endless loop, is stopped and not run for the rest of the render. The property keeps its own value, and a selector returns 100%. Every property and selector with exactly the same script text stops with it.
- The time limit applies to each run: once per frame for a property, and once per element for a selector.
- A failed expression selector returns 100%. As the first selector of its animator, it selects everything. After other selectors, it keeps their selection.
- An expression selector that does not compile is dropped. If it was the animator's only selector, the animator applies to the whole text. Otherwise its other selectors still apply.
- Render and inspect several frames where the result should differ from the base. For oscillation, check opposing phases, not only whole periods where the offset is zero.
- Fix a failing expression. Don't silently replace a requested expression with keyframes.

### Expression functions and values

| Expression API | Meaning and usage |
| --- | --- |
| `time`, `value` | Current time in seconds, and the property's value without this expression |
| `thisComp.width`, `.height`, `.duration`, `.numLayers`, `.frameDuration` | The containing composition's size, duration in seconds, layer count, and seconds per frame. Use `thisComp.frameDuration`, not an assumed bare global. In the main composition, `.duration` is `(op − ip) / fr`. In a precomposition, it is the precomposition layer's own `op − ip` in its parent, in seconds, not the precomposition's length. A frame render keeps the composition's timing, so `.duration` matches a video render. `.numLayers` counts every layer except audio layers. A plan's watermark changes none of these. |
| `numKeys`, `key(n)`, `nearestKey(t)` | The property's key count, and keys with `index`, `time` and `value`. Keys count from 1. Check `numKeys` first, call `key()` and `nearestKey()` only on a keyframed property, and keep `n` from 1 to `numKeys`. Keyframes that all hold one value count as none here. |
| `thisComp.layer(nameOrInd)`, `thisLayer` | A layer's `position`, `anchorPoint`, `scale`, `rotation` or `opacity`, directly or under `.transform`. Only the same composition. A number is the layer's `ind`, not its array place. A text is always a name, so `"3"` is not `ind` 3. Of layers sharing a name, the first in `layers` counts. A null's or camera's `opacity` reads 100. A layer also has `index` (its `ind`), `inPoint` and `outPoint` in seconds, and `name`, always an empty string. The globals `inPoint` and `outPoint` are the current layer's. |
| `valueAtTime(t)`, `velocityAtTime(t)` | The property's base animation at a time in seconds, and its velocity in units per second. Functions of the current property, not methods on other layers' values. |
| `wiggle(frequency, amplitude, octaves)` | Repeatable noise around `value`: frequency in cycles per second, amplitude in property units, optional octaves clamped to 1–4. A fourth or fifth argument is ignored. The noise follows the layer's name: renaming a layer changes its wiggle, and layers with the same name wiggle alike on the same property. |
| `linear(t,tMin,tMax,v1,v2)`, `ease(...)`, `easeIn(...)`, `easeOut(...)` | Interpolate between number or matching vector endpoints, clamped to the interval. The forms `(t,v1,v2)` use the interval 0–1. |
| `clamp(value,min,max)` | Bound a number, or each component, between two numbers. A one-item list such as `[5]` reads as its number. |
| `smooth(width,samples)` | Average the base animation across a window in seconds. Defaults: `0.4` and `5`. |
| `loopOut(type,count)`, `loopIn(type,count)` | Extend a keyed track after its last key or before its first. Use at least two keys at different times. `count: 0` uses the whole keyed segment; a positive count limits the keyframe intervals. |
| `loopOutDuration(type,seconds)`, `loopInDuration(type,seconds)` | Pick the loop segment by duration. Use a positive, explicit duration. |
| `Math`, ordinary JavaScript | Arithmetic, lists, conditions, bounded loops, functions and standard math. Return the final value, and don't rely on state from a previous frame. |

Loop types are `cycle` (repeat), `pingpong` (alternate direction), `offset` (repeat with accumulated displacement) and `continue` (extend the end velocity). Loop helpers need an authored keyframed track: preserve its keys. A loop extends values, not the layer's `ip` and `op`.

- Don't use expressions to recover authored layer names, indices or visibility bounds. Keep names and relationships from the inspected document, and read `data.json` for editable copy.
- Preserve exported `$bm_sum`, `$bm_sub`, `$bm_mul`, `$bm_div`, `$bm_mod` and `$bm_neg` helpers.
- Expression selectors do per-text selection, not transform placement ([per-character expression selectors](#per-character-expression-selectors)).

### Layer relationships and loops

Read the document before choosing layer names or indices. `thisComp.layer("Leader").transform.position` reads a layer in the same composition, by name or `ind`. Its transform values are values, not After Effects property objects. Positions are local to their parents, so a direct offset fits only layers sharing a coordinate space. A follower's position script there could be:

```javascript
var leaderPosition = thisComp.layer("Leader").transform.position;
[leaderPosition[0] + 120, leaderPosition[1], leaderPosition[2]];
```

- Use the actual inspected name instead of inventing `Leader`. Keep these references through renames and restacks.
- Keep dependencies one-way, never circular.
- A referenced layer's expression runs before its value is returned. The two scripts share one scope, so give their top-level variables different names.
- There are no world-space conversion functions and no cross-composition lookup.

This complete property repeats a rotation between −12 and 12 degrees every second at 30 fps, playing the authored segment forward and backward:

```json
{"a":1,"k":[{"t":0,"s":[-12],"e":[12],"o":{"x":0.333,"y":0.333},"i":{"x":0.667,"y":0.667}},{"t":30,"s":[12]}],"x":"loopOut(\"pingpong\");"}
```

Key times are frames. The loop is a function of time: it shows while the layer is visible, and it does not extend the layer's `ip` or `op`. A looping parent keeps moving its children while it is hidden or outside its own `ip` and `op`. On an existing track, add the loop without replacing its keys, unless the caller asks for a new track.

### Per-character expression selectors

Use an expression selector in a text animator, not on the text document. It returns a percentage from −100 to 100 that weights the animator's properties:

| Value | Meaning |
| --- | --- |
| `textIndex` | The element's position in the selected domain, from 1 |
| `textTotal` | The number of elements in the domain |
| `selectorValue` | The incoming selection percentage |
| `value` | The base Amount, 100, not the character position |
| `time` | Seconds, to animate the selection |

This complete `t.a` entry sends a vertical wave across the characters, 24 pixels high with a 1.5-second period. Keep the layer's `t.m` grouping on characters:

```json
{"a":{"p":{"a":0,"k":[0,24,0]}},"s":{"t":1,"b":1,"x":"100 * Math.sin(2 * Math.PI * time / 1.5 - (textIndex - 1) * 0.5);"}}
```

- Append it to the existing animator list to keep other animation, and inspect several frames for readability and clipping.
- A selector weights every property in its animator. Use separate animators for different selections.
- It multiplies the selection of the selectors before it, as After Effects' Intersect does, and starts from full selection when it comes first. So returning `selectorValue` after a range selector squares partial selections.
- Selectors can use composition size and duration, `thisComp.frameDuration`, math and interpolation helpers. They cannot use `thisLayer`, `thisComp.layer`, `numKeys`, keyframe sampling, or loop helpers that need a property track.
- `wiggle` gives every element of a selector the same amount: use `textIndex` for per-element variation.
- Return one amount, not separate X, Y and Z amounts.

### Edge cases

- An `x` that is not a string cannot run, and the property animates without it (`warnings`).
- A single number on position, anchor or scale sets all three axes to it. A two-item list keeps the base Z. Items past the third are dropped, and an empty list reads as 0 on every axis.
- `clamp`: a `min` or `max` given as a list of two or more numbers is ignored, and that side is left unbounded. The other bound still applies.
- `linear` or `ease` with four arguments reads them as `(t,v1,v2)` and ignores the fourth. A `tMax` below `tMin` swaps the two.
- An unknown loop type means `cycle`. A track with one key gives NaN.
- `loopOutDuration` with 0 or no duration loops from the layer's in point to the last key. `loopInDuration` with 0 or no duration loops from the first key to the out point.
