# Code blocks

`code` from `framescript/code` makes a block of monospace text with a colour for each token, a caret and a line highlight. Four presets animate it: `type`, `blink`, `highlightLine` and `change`.

```ts
import { add, camera, timeline, video, wait } from "framescript"
import { blink, change, code, highlightLine, type } from "framescript/code"
import { PerspectiveCamera } from "three"

const SOURCE = `const ball = yield* add(circle({ radius: 0.4 }))
yield* tween(ball.position, { y: 2 }, 0.6)
yield* wait(1)`

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)

    const block = yield* add(code(SOURCE, { language: "ts", fontSize: 0.28 }), {
      position: [-4, 1, 0],
    })
    yield* type(block, { duration: 3 })
    yield* blink(block.caret, { duration: 1 })
    yield* highlightLine(block, 2)
    yield* change(block, "0.6", "1.2")
    yield* wait(1)
  })
)
```

A block's origin is its top left corner. `add` waits until the block is laid out, which takes no scene time. After that its parts and measurements can be used.

## The source

The source is a string. To show a file of the video, import its text with `?raw`; a scene can show its own source this way. `lines` picks a range, counted from 1, both ends included.

```ts
import { add } from "framescript"
import { code } from "framescript/code"
import source from "./release.ts?raw"

const block = yield* add(code(source, { lines: [12, 14], language: "ts" }))
```

TypeScript needs to be told once per video what a `?raw` import is. Put this in a `.d.ts` file under the video's sources, for example `src/raw.d.ts`:

```text
declare module "*?raw" {
  const source: string
  export default source
}
```

What happens to the source before it is shown:

- The whole source is tokenized before the range is cut, so a range that starts inside a comment or a template literal is still coloured as one.
- The indentation the shown lines share is removed, so a range from deep inside a file starts at the left edge. `dedent: false` keeps it.
- A tab becomes `tabSize` spaces (default 2).
- A range that is not inside the source throws an error that names the lines the source has.

## Languages and colours

`language` is `"ts"`, `"js"`, `"json"`, `"shell"` or `"text"`. The default is `"text"`, which colours nothing. The tokenizer never fails: what it does not understand is drawn as plain text.

Each token has one of ten kinds: `keyword`, `string`, `number`, `comment`, `punctuation`, `identifier`, `function`, `property`, `operator` and `plain`. A theme has one colour for each kind, plus `caret` and `highlight`. The default is [`darkTheme`](/docs/framework/reference/code.md#darktheme), made for a dark ground. `theme` replaces single entries:

```ts
import { add } from "framescript"
import { code } from "framescript/code"
import { KIT } from "framescript/kit"

const loud = yield* add(
  code("const speed = 2", {
    language: "ts",
    theme: { keyword: "#ff6467", number: "#fe9a00" },
  })
)
// The interface kit's greys, for code that should not compete with an accent.
const quiet = yield* add(
  code("const speed = 2", { language: "ts", theme: KIT.code })
)
```

## Font and size

| Option       | Does                                                                      | Default  |
| ------------ | ------------------------------------------------------------------------- | -------- |
| `fontSize`   | The font size in world units.                                             | `32`     |
| `lineHeight` | Line height as a multiple of the font size.                               | `1.5`    |
| `fontWeight` | Regular or bold (600 and above) of the bundled font.                      | regular  |
| `family`     | `"mono"`, the bundled monospace, or `"sans"`, the typeface of `text()`.   | `"mono"` |
| `font`       | The address of a monospace `.ttf`, `.otf` or `.woff` file to use instead. | none     |
| `caret`      | Whether the caret is drawn.                                               | `true`   |

The default `fontSize` of 32 suits a scene measured in pixels. In a scene a few units high, as in the samples here, set it to a fraction of a unit.

## Parts and measurements

Once the block is added:

- `block.lines`, `block.tokens` and `block.chars` are arrays of objects with a position, rotation, scale and `opacity`. `lines[i]` is line `i` of the block, also when it is empty. White space has no part. A token that spans lines is one part for each line.
- `block.token("0.6")` finds a token by its text; a second argument picks a later one with the same text, counted from 0. It returns `undefined` when there is none.
- `block.model` holds every line and token with its kind, line and column, and is known before the block is added.
- `block.width` and `block.height` are the block's size. `block.advance` is the width of one character.
- `block.caret` is a bar one character high. It stands after the last character. `block.caretAt(index)` gives the position before any character of `block.content`.
- `block.highlight` is a band behind the text. It has no width until `highlightLine` gives it one.
- `block.lineSpan(line)` gives the positions in `block.content` where a line starts and ends. `block.lineBox(line)` gives the band a line occupies. Both count lines from 1 and throw when the block has no such line.

```ts
import { add, stagger, tween } from "framescript"
import { code } from "framescript/code"

const block = yield* add(
  code('const name = "Framescript"\nconst speed = 2', { language: "ts" })
)
// Dim everything but one token.
yield* stagger(
  0.02,
  ...block.tokens
    .filter((token) => token !== block.token("2"))
    .map((token) => tween(token, { opacity: 0.25 }, 0.2))
)
```

## Typing

`type` hides each character until its turn and then shows it at once, with the caret after the last one typed. The rhythm is a person's: uneven, with a breath after a word and a longer one before a new line. It comes from `seed`, so every render types the same way.

```ts
import { add } from "framescript"
import { blink, code, type } from "framescript/code"

const block = yield* add(
  code("yield* wait(1)\nyield* wait(2)", { language: "ts" })
)
// Line 1 at the default rate of 14 characters a second.
yield* type(block, { ...block.lineSpan(1), seed: 3 })
yield* blink(block.caret, { duration: 1, period: 0.5 })
// Line 2 in exactly one second.
yield* type(block, { ...block.lineSpan(2), duration: 1 })
```

Give `rate` (characters a second) or `duration` (seconds in all). `from` and `to` are positions in `block.content`. `blink` shows the caret for half a `period` and hides it for the other half, and ends shown. [`typingTimes`](/docs/framework/reference/code.md#typingtimes) gives the rhythm as numbers, to move something else in step with the typing.

## Highlighting a line

`highlightLine(block, line)` puts the band on a line, counted from 1. The first time it grows across the line from the left. After that it travels from the line it is on. Line 0 takes it away again. `fit: "line"` makes the band as wide as the line's own text in place of the block.

```ts
import { add } from "framescript"
import { code, highlightLine } from "framescript/code"

const block = yield* add(code("first()\nsecond()", { language: "ts" }))
yield* highlightLine(block, 1)
yield* highlightLine(block, 2, { fit: "line", duration: 0.3 })
yield* highlightLine(block, 0)
```

## Changing a literal

`change(block, token, to)` turns one token into another text. A number counts to the new number. Anything else settles out of scrambled letters. When the new text has another length, what follows on the line moves over by the difference; nothing before the token moves.

```ts
import { add } from "framescript"
import { change, code } from "framescript/code"

const block = yield* add(
  code('yield* tween(ball, { color: "red" }, 0.6)', { language: "ts" })
)
yield* change(block, "0.6", "1.2", { duration: 0.8 })
yield* change(block, '"red"', '"coral"', { steps: 6, seed: 2 })
```

The token is one of `block.tokens` or the text of one, which finds the first token with that text. `change` throws when the block has no such token. [`changeContents`](/docs/framework/reference/code.md#changecontents) returns the texts a token passes through.

## Limits

- The content of a block is fixed once it is made. `change` covers the token with texts of its own.
- After a `change` to a text of another length, `caretAt` and `type` still count in the original text, and the caret does not move with the line.
- With `family: "sans"` or another proportional font, a `change` to a text of another length moves what follows by whole character widths, which is only exact in a monospace font.
- Lines do not wrap. There are no line numbers and no panel behind the block; [`listing`](/docs/framework/objects/kit.md#code-on-a-plate-or-a-bar) from the interface kit puts a block on a plate.
- The bundled font covers Latin only. A character it lacks, such as an arrow or a box-drawing character, is a warning, and a `?` stands in for it. Use other characters, or give the block a `font` that has it.

## See also

- Examples: code/typing, code/change, code/reading
- [The interface kit](/docs/framework/objects/kit.md) for code on a plate or a bar
- [Text](/docs/framework/objects/text.md) for parts, fonts and the text presets
- [Assets and loading](/docs/framework/media/assets.md) for `?raw` imports
- [Reference: framescript/code](/docs/framework/reference/code.md)
