# Text

`text(content, style)` from `framescript/text` makes a text object to pass to `add`. Its lines, words and characters are objects of their own, so every step that moves an object moves a part of a text. The presets that bring text in, mark it and set it on a path are in `framescript/motion`.

```ts
import { add, camera, timeline, video, wait } from "framescript"
import { highlight, revealWords } from "framescript/motion"
import { backdrop } from "framescript/shapes"
import { text } from "framescript/text"
import { PerspectiveCamera } from "three"

export default video(
  { width: 1920, height: 1080, fps: 60 },
  timeline(function* () {
    const lens = yield* add(new PerspectiveCamera(32, 16 / 9, 0.1, 100), {
      position: [0, 0, 14],
    })
    yield* camera(lens)
    yield* add(backdrop("#0e0e0e"))

    const title = yield* add(
      text("A video is a program,\nand a program can be read.", {
        fontSize: 0.7,
        lineHeight: 1.5,
        color: "#ededed",
        anchorX: "center",
        anchorY: "middle",
      })
    )
    yield* revealWords(title, { stagger: 0.12, duration: 0.5 })
    yield* highlight(title, { match: "a program", color: "#ff6467" })
    yield* wait(1.6)
  })
)
```

## Making a text

In the content, `\n` starts a new line. The layout is worked out while `add` waits, which takes no scene time. After that the text has its parts, and its `width` and `height`.

Content and style are fixed once a text is made. For a number that changes, use a [counter](#numbers-that-count); for any other text that changes, a [flipbook](#text-that-changes).

The style:

| Option          | What it is                                                                                                    | Default          |
| --------------- | ------------------------------------------------------------------------------------------------------------- | ---------------- |
| `fontSize`      | The size, in the units of where the text is: world units, or pixels on [the screen layer](/docs/framework/scene/screen.md) | 48               |
| `fontWeight`    | Regular or bold of the bundled font: `"bold"`, or 600 and above, is bold                                      | `"normal"`       |
| `font`          | The address of a `.ttf`, `.otf` or `.woff` file                                                               | the bundled font |
| `color`         | The fill colour                                                                                               | white            |
| `colorRanges`   | Colours for runs of characters: `{ 0: "#fff", 6: "#f80" }` colours from the seventh character on              | none             |
| `maxWidth`      | The width at which lines wrap; without it only `\n` breaks a line                                             | none             |
| `align`         | How lines are aligned in the block: `"left"`, `"center"`, `"right"`, `"justify"`                              | `"left"`         |
| `lineHeight`    | The line height as a multiple of the font size                                                                | the font's       |
| `letterSpacing` | Extra space between characters                                                                                | none             |
| `anchorX`       | Which point of the block is at the object's origin, across: `"left"`, `"center"`, `"right"`                   | `"left"`         |
| `anchorY`       | The same, down: `"top"`, `"middle"`, `"bottom"`, `"top-baseline"` and others                                  | `"top"`          |
| `sdfGlyphSize`  | The resolution of each glyph: 64 rounds the corners of large titles, 256 is the sharpest                      | 128              |

The default size of 48 suits the screen layer. In a scene measured in units, always give a `fontSize`.

With `colorRanges`, every character takes its colour from the ranges and `color` is not used, so give position 0 a colour. The colours are fixed, like the content.

Every glyph of every font a video draws at one `sdfGlyphSize` is kept in one atlas: a texture 2048 pixels wide whose height doubles as it fills. In 8192 rows it holds 1024 glyphs at 256, 4096 at 128 and 16384 at 64. Past 8192 rows WebGL can fail to grow it, as Chrome on macOS does, and every text at that size then draws nothing. So the run counts the glyphs each atlas will hold: a warning at the `add` of the text that takes an atlas past 8192 rows names the fonts behind it, and past 16384 rows, more than most graphics cards hold, it is an error. The atlas belongs to the page and keeps every glyph any video on it drew: a collection's videos, shown side by side in the studio, fill it together, so a video whose own glyphs fit is warned too once the page's atlas passes, and the message says how many glyphs the others drew. Give text that stands far from the camera a smaller `sdfGlyphSize`, or use fewer fonts; each weight of a family is a font of its own.

### Fonts

The bundled font is Inter, in regular and bold. It comes with Framescript, so nothing is fetched, and it covers Latin only. For another font, load a file and give its address as `font`. The file then decides the weight.

```ts
import { add, load } from "framescript"
import { text } from "framescript/text"

const mono = yield* load.font("/examples/assets/mono.woff")
yield* add(text("fonts\nby file", { font: mono, fontSize: 0.5 }))
```

A character the font has no glyph for does not stop the scene. A "?" stands in for it, and a warning at the `add` names the character.

## Parts

A text has `lines`, `words` and `chars`: arrays of objects in reading order. A line holds its words and a word its characters in `parts`, so their motions add up. White space has no part.

Each part has a position, a rotation, a scale and an `opacity`, and turns about its own middle. Animate them like any object's:

```ts
import { add, by, from, stagger } from "framescript"
import { text } from "framescript/text"

const title = yield* add(
  text("Every word on its own", { fontSize: 0.7, anchorX: "center" })
)
yield* stagger(
  0.08,
  ...title.words.map((word) => from(word.position, { y: by(-0.3) }, 0.5))
)
```

A part also has a `clip`. Above 0, the part is cut off at the edges of its own box at rest, so what moves out of the box is not drawn. Each character's cut also takes in its own ink where it stands at rest, so a descender that reaches below the line's box shows whole once the character is home. That is what lets a line rise into place from behind its lower edge; `rise` and `riseLines` do it for you. The box is the part's own, in the text's own space, wherever the text stands and however its groups turn. A copy set behind a text as its shadow is cut at a box of its own, so offset it through its `lines` rather than as a whole: its lines then move out of the same box the text's do, and nothing of the shadow shows below the text's edge while it rises.

A part knows its `content`, its `width` and `height` at rest, and for a character its `index` in the content.

## The text presets

All of these are in `framescript/motion` and take a text made with `text()`.

| Preset                                      | What it does                                                                           |
| ------------------------------------------- | -------------------------------------------------------------------------------------- |
| `rise`                                      | Letters, words or lines rise one after another from behind their line; nothing fades   |
| `revealChars`, `revealWords`, `revealLines` | Brings the text in part by part, each fading in and rising into place                  |
| `riseLines`                                 | Each line rises from behind its own lower edge; nothing fades                          |
| `typewriter`                                | Characters appear one by one, each at once; `interval` is the time between two (0.045) |
| `highlight`, `underline`                    | Draws a bar behind a run of text, or a line under it, from left to right               |
| `setOnPath`, `slideOnPath`                  | Sets a one-line text along a path, or moves it along                                   |
| `captions`                                  | Lights the words up one by one at given moments                                        |

`rise` is how a title comes in by default, and what [taste](/docs/framework/taste.md) expects of one. Its letters (`by: "word"` or `"line"` for those) come up from a line below, each line cut off at its own box until the last piece stands, as a line of a web page rises with its overflow hidden. The defaults are in `RISE`: 0.9 seconds a piece, 0.028 between letters, 0.11 between words and 0.12 between lines, a drop of 1.05 lines and `expoOut`. A piece whose glyphs reach further than a line, as tall letters do in a tightly set title, drops that much further, so none of it peeks over the edge before its turn. Each can be given: `duration`, `stagger`, `drop`, `ease` and `delay`.

```ts
import { add, all } from "framescript"
import { RISE, rise } from "framescript/motion"
import { text } from "framescript/text"

const title = yield* add(text("Every frame is code.", { fontSize: 1 }))
const line = yield* add(
  text("Letters, words or lines.", { fontSize: 0.36 }),
  {
    position: [0, -1, 0],
  }
)
yield* all(rise(title), rise(line, { by: "word", delay: RISE.duration / 2 }))
```

The reveals take `stagger`, the seconds between one part and the next, and `distance`, how far a part rises: half its height unless you say otherwise, and 0 only fades.

```ts
import { add, sequence } from "framescript"
import { revealLines, typewriter, underline } from "framescript/motion"
import { text } from "framescript/text"

const lines = yield* add(
  text("A video is a file.\nThe file is the timeline.", {
    fontSize: 0.7,
    lineHeight: 1.4,
  }),
  { position: [-4, 2, 0] }
)
const typed = yield* add(
  text("Every frame comes from it.", { fontSize: 0.5 }),
  {
    position: [-4, -1, 0],
  }
)
yield* sequence(
  revealLines(lines, { stagger: 0.25, distance: 0.3, duration: 0.6 }),
  typewriter(typed, { interval: 0.05 }),
  underline(lines, { match: "the timeline", color: "#ff6467" })
)
```

`highlight` and `underline` name their run with `match`, as it stands in the content; without it the whole text is marked. A run that stands in two lines gets a mark in each. A `match` the text does not contain is an error.

### Text on a path

The path is SVG path data, points or contours, as for [`path`](/docs/framework/objects/shapes.md#paths), in the text's own space: a `path` of the same data added at the same place lies under the text. `at`, `from` and `to` say where the text begins, as a share of the path's length.

```ts
import { add } from "framescript"
import { setOnPath, slideOnPath } from "framescript/motion"
import { text } from "framescript/text"

const WAVE = "M-6,0 C-4,-3 -2,-3 0,0 S4,3 6,0"

const line = yield* add(
  text("every letter follows the line", { fontSize: 0.5, anchorY: "middle" })
)
yield* setOnPath(line, WAVE, { at: 0 })
yield* slideOnPath(line, WAVE, { from: 0, to: 0.42, duration: 2.4 })
```

### Captions

`captions(target, words, options)` takes one timing for each word of the text, in order: `{ start, end }` in seconds from the start of the step, as a transcript gives them. A word is dim (an opacity of 0.3, the `dim` option) until its moment and bright from then on. The number of timings must be the number of words.

```ts
import { add } from "framescript"
import { captions } from "framescript/motion"
import { text } from "framescript/text"

const WORDS = [
  { text: "Every", start: 0.2, end: 0.5 },
  { text: "word", start: 0.5, end: 0.8 },
  { text: "lights", start: 0.9, end: 1.25 },
  { text: "up.", start: 1.25, end: 1.5 },
]

const caption = yield* add(
  text(WORDS.map((word) => word.text).join(" "), {
    fontSize: 0.6,
    anchorX: "center",
  })
)
yield* captions(caption, WORDS)
```

## Numbers that count

`counter(value, options)` is a number that is text. Its `value` is a number on the timeline, and what is drawn is that value in a fixed format. Tween `value`, or use `countTo` from `framescript/motion` (1.2 seconds by default).

```ts
import { add } from "framescript"
import { countTo } from "framescript/motion"
import { counter } from "framescript/text"

const cost = yield* add(
  counter(1250, { fontSize: 0.9, decimals: 2, prefix: "$", align: "right" })
)
yield* countTo(cost, 4800, { duration: 2 })
```

The format: `decimals` (0), `thousands` (the separator, `","`; an empty text leaves the digits together), `point` (`"."`), `prefix` and `suffix`. A minus sign stands before the prefix. Every digit takes the room of the widest, so the number does not jitter while it runs, and `align` says which end stays where the counter is: `"left"` (the default), `"center"` or `"right"`. `digits` is the most digits before the point it can show, 9 by default. The rest of the options are the text's style.

## Text that changes

`flipbook(contents, style)` is one text per content, all laid out before the scene starts, of which one shows at a time. `flip` from `framescript/motion` steps through them from the first to the last (1.5 seconds by default, evenly spaced).

Two helpers in `framescript/motion` write contents: `count(from, to, options)` writes evenly spaced numbers, and `scramble(content, options)` writes the text with random characters that settle into it from the left. The characters come from a `seed`, so every render is the same.

```ts
import { add, all } from "framescript"
import { count, flip, scramble } from "framescript/motion"
import { flipbook } from "framescript/text"

const state = yield* add(
  flipbook(["Draft", "Review", "Final"], { fontSize: 0.9 }),
  {
    position: [-4, 1.5, 0],
  }
)
const share = yield* add(
  flipbook(count(0, 100, { suffix: "%" }), { fontSize: 0.9 }),
  {
    position: [-4, 0, 0],
  }
)
const word = yield* add(
  flipbook(scramble("EVERY FRAME", { steps: 28, seed: 7 }), {
    fontSize: 0.9,
  }),
  { position: [-4, -1.5, 0] }
)
yield* all(
  flip(state, { duration: 2 }),
  flip(share, { duration: 2 }),
  flip(word, { duration: 2 })
)
```

Each content is a text of its own, in `frames`. Characters cannot be animated one by one across a change.

## A line that builds

`buildLine(content, options)` is a line of a few words that builds from the middle: the words arrive one a beat and the line slides to keep what has arrived centred, so it locks centred on the last. It suits a three to five word rhythm line. It is a [piece](/docs/framework/objects/kit.md#pieces): add it, then play `enter()`, `hold(seconds)` and `exit()`.

```ts
import { add } from "framescript"
import { LOOKS } from "framescript/kit"
import { buildLine } from "framescript/text"

const line = yield* add(
  buildLine("Plan it. Ship it. Repeat.", {
    look: LOOKS.editorial,
    accentWord: "Ship",
  })
)
yield* line.enter()
yield* line.hold(1)
yield* line.exit()
```

Each look builds it its own way, and `variant` names one: `rise` (editorial: each word rises from under its line), `push` (kinetic: each word pushes the line), `light` (gallery: words fade up slowly), `edge` (swiss: flush, never re-centring), `depth` (spatial: words come forward out of depth), `type` (signal: words type in) and `float` (warm: words float in on a spring). Its options are `look`, `variant`, `accentWord` (written in the accent), `beat` (seconds between words), `size` (a role of the look or world units) and `maxWidth` (12 world units unless given; a longer line is scaled down to fit).

## Limits

- A text's content and style do not change after it is made.
- The bundled font covers Latin only, in regular and bold.
- A text is flat. For solid letters, see `extrudeText` in [Shapes](/docs/framework/objects/shapes.md#solids).
- `setOnPath` and `slideOnPath` are for a text of one line.
- `text.complete` is `false` when a glyph could not be matched to a character, as can happen with ligatures and complex scripts. Such a glyph cannot be animated.

## See also

- [Layout](/docs/framework/objects/layout.md): rows and columns that measure text
- [The screen layer](/docs/framework/scene/screen.md): text in pixels that no camera moves
- [Motion](/docs/framework/animation/motion.md): the other presets in `framescript/motion`
- [Assets](/docs/framework/media/assets.md): `load.font`
- Examples: text/rise, text-reveals/reveals, text/rise-lines, text/marks, text/on-path, text/captions, text/counter, layout/flipbook
- [Reference: framescript/text](/docs/framework/reference/text.md), [Reference: framescript/motion](/docs/framework/reference/motion.md#revealchars)
