# SDK: Layers

> A graphic layer is DOM a piece draws, made by a component (defineComponent()) or written in place (custom()). Here: both, the layer's ctx, the helpers of @allyhub/sdk/dom and @allyhub/sdk, and the starter components. A layer's timing (at, until, dur) and stacking (z) are in video.md; footage layers in footage.md.

Source: https://allyhub.com/docs/reference/sdk/layers · AllyHub 0.10.0
Index of all docs: https://allyhub.com/llms.txt

## `custom()`

A graphic layer written in the piece, for what no component does. `custom({ mount?, render, at?, until?, dur?, z? })`:

```ts

  key: "year",
  dur: 3,
  layers: [
    custom({
      at: 0.5,
      mount(el, ctx) {
        const L = layout(ctx);
        const label = tag(
          h("div", { fontSize: 240 * L.k, fontWeight: 900 }),
          "year",
        );
        label.textContent = "2026";
        el.append(
          h(
            "div",
            {
              position: "absolute",
              inset: 0,
              display: "grid",
              placeItems: "center",
            },
            [label],
          ),
        );
      },
      render(el, t, ctx) {
        const label = one(el, "year");
        if (!label) return;
        const x = tween(t, {
          start: ctx.layer.start,
          dur: 0.4,
          ease: ease.out,
        });
        label.style.opacity = String(x);
        label.style.transform = `scale(${String(1.4 - 0.4 * x)})`;
      },
    }),
  ],
});
```

## `defineComponent()`

A component is a function that makes a graphic layer from its props and the layer's options, in one object.

```ts file=components/badge.ts

  value: string;
  label: string;
  settle?: Time;
}>({
  name: "badge",
  label: { en: "Badge" },
  summary: "A number with a label under it.",
  props: {
    value: text({ max: 6 }),
    label: text({ max: { "16x9": 40, "9x16": 24 } }),
    settle: time({ optional: true }),
  },
  defaults: { label: "" },
  examples: { pilots: { value: "3", label: "pilot teams" } },
  mount(el, p, ctx) {
    const L = layout(ctx);
    const value = tag(
      h("div", { fontSize: 160 * L.k, color: "var(--ak-color-accent)" }),
      "value",
    );
    value.textContent = p.value;
    const label = h("div", {
      fontSize: 48 * L.k,
      fontFamily: "var(--ak-font-body)",
    });
    label.textContent = p.label;
    el.append(
      h("div", { position: "absolute", left: L.left, top: L.top }, [
        value,
        label,
      ]),
    );
  },
  render(el, t, p, ctx) {
    const value = one(el, "value");
    if (!value) return;
    value.style.opacity = t < (p.settle ?? ctx.layer.start) ? "0.4" : "1";
  },
});
```

```ts file=launch/film/parts.ts

// Its props and the layer's options in one object; settle is given as a reference to the part's anchor.
  key: "teams",
  dur: 3,
  anchors: { live: 1.2 },
  layers: [
    badge({ value: "3", label: "pilot teams", settle: "@live", at: 0.5 }),
  ],
});
```

| Field | What it is |
| --- | --- |
| `name` | The component's name, unique in the project |
| `label`, `summary` | Its name (default `name`) and one line on what it is for: a string, or by language |
| `props` | The props' semantic types, plain data (below) |
| `defaults` | Default prop values |
| `examples` | Named example props |
| `hidden` | Hides a deprecated component |
| `mount(el, props, ctx)` | Lays the layer out once: builds its elements, may measure text |
| `render(el, t, props, ctx)` | Sets everything that moves from `t` alone |

`at`, `until`, `dur` and `z` are the layer's options (`LAYER_OPTIONS`): a prop cannot have those names (`defineComponent` throws). A layer's length and still belong to its part.

### Layers in a frame

In place of `mount` and `render`, a component may give `layers(props, { width, height })`: layers of the layer contract (`custom()`, other components) laid out in a frame of that size in pixels. It is the form a deck's `prs.components.add` takes, and one component of either form can be placed by a video part, a deck's shape and a doc's `<Component>` ([docs.md](https://allyhub.com/docs/reference/sdk/docs.md#components)); a one-layer component fills the frame it is given.

```ts file=components/plan-card.ts

  name: "plan-card",
  label: { en: "Plan card" },
  props: { name: text(), price: number({ min: 0 }) },
  defaults: { price: 0 },
  layers: (p, frame) => [
    custom({
      mount(el) {
        el.style.cssText = `position:absolute;inset:0;padding:${String(frame.width * 0.05)}px;background:var(--ak-color-bg);font-family:var(--ak-font-body)`;
        el.textContent = `${p.name}: $${String(p.price)}`;
      },
      render() {},
    }),
  ],
});
```

In a video part, list its layers: `layers: [...PlanCard.layersIn({ name: "Pro", price: 12 }, { width: 1920, height: 1080 })]`.

**Prop types** (from `@allyhub/sdk`, plain data; each takes `label`, `examples` and `optional`):

| Function | What it is | Its limits |
| --- | --- | --- |
| `text(o?)` | Text on screen | `max` (one number, or per preset format), `min`, `multiline` |
| `time(o?)` | A moment ([below](#time-props)) | |
| `asset(o?)` | Media: an import or `ctx.asset(path)` | `kind` |
| `color(o?)` | A look variable, such as `var(--ak-color-accent)` | |
| `number(o?)` | A number | `min`, `max`, `step` |
| `boolean(o?)` | A switch | |
| `list(of, o?)` | A list | `min`, `max` |
| `object(fields, o?)` | An object | |

### Time props

A prop declared `time()` (also inside `list()` and `object()`) is typed `Time` in the component. Where the layer is made it takes a word reference or seconds (`"live"`, `"@press+0.2"`, `1.2`: [speech.md](https://allyhub.com/docs/reference/sdk/speech.md)); by the time `mount` runs it is seconds from the part's start. Only `time()` props take word references.

### `mount` and `render`

- `mount` runs once for each element a layer is drawn into, before any `render` of it: once per part that lists it, and again for a cover. Keep what `render` needs on the element (find it again with `one`, or a `WeakMap` keyed by `el`), not in a variable the elements share. The fonts the look and the text need have loaded by then, so it may measure.
- `render(el, t, …)` gets `t`, seconds from the part's start, and runs only between the layer's `at` and `until`: an entrance counts from `ctx.layer.start`. It sets every moving property from `t` alone, never from the frame before: the same moment draws the same frame in any order (AK-D002). What a layer may and may not do to stay deterministic is in [contract.md](https://allyhub.com/docs/reference/sdk/contract.md).
- A style value the browser does not accept (`fontWeight: "900px"`, `width: "760"`) is dropped by the browser; while checking, every inline style set is watched and such a value is AK-R004.
- Text inside an element marked `data-ak-picture` is part of a picture (a mocked interface the frame crops on purpose): the frame's text checks leave it out.

### What the contract relies on

- **The look by its variables**: colours and fonts as `var(--ak-color-*)` and `var(--ak-font-*)` ([video.md](https://allyhub.com/docs/reference/sdk/video.md#the-look)) follow the project's look; a literal colour does not. A `color()` prop holds a look variable. A deck's component follows the deck's theme with `var(--ak-theme-*)` ([slides.md](https://allyhub.com/docs/reference/sdk/slides.md#components)).
- **Text as text**: the helpers set text as text nodes (`textContent`), so a string never becomes markup.
- **Every format**: lay out from `ctx.dims`, `ctx.content` or `layout(ctx)`, not by the format's name: a custom `WxH` has no preset's name, and a changed `safe` keeps the format's.

## The layer's `ctx`

`mount` and `render` get a `StageContext`:

| Name | What it is |
| --- | --- |
| `ctx.look` | The look (also the CSS variables `--ak-color-*`, `--ak-font-*`, `--ak-motion-beat`) |
| `ctx.format` | The format's name: `"9x16"`, `"1280x720"`; a deck's may be `"a4"` |
| `ctx.dims` | `{ width, height, orient, safe }` ([video.md](https://allyhub.com/docs/reference/sdk/video.md#formats)) |
| `ctx.combo` | The combo. A layer may read the dimensions and its own part's slot, never another slot's pick (AK-X005): a part is rendered once for every combo that has it |
| `ctx.dur` | The part's length, seconds |
| `ctx.layer` | `{ start, end }`: this layer's window, seconds from the part's start |
| `ctx.enter`, `ctx.exit` | `{ start, end }`: where a transition shares the screen with the part before (`enter`, from before 0) or after (`exit`, to past `ctx.dur`), seconds from the part's start; absent at a cut. An entrance that starts at `ctx.enter.end` plays once the part shows alone |
| `ctx.asset(path)` | Media at a path relative to the piece's file |
| `ctx.optionalAsset?.(path)` | Media that may not be there (a scenery's bake): `undefined` when it is not, with no problem; the part is drawn again once it is made |
| `ctx.words()` | The part's words on its own clock, `[{ text, start, end }]`; empty without speech |
| `ctx.at(ref)` | Seconds from the part's start of a word reference or an anchor |
| `ctx.captions(opts?)` | The caption cues shown in this part, each with its words ([speech.md](https://allyhub.com/docs/reference/sdk/speech.md)) |
| `ctx.face(t, id?)`, `ctx.faces(t)` | Faces on the frame at `t` ([footage.md](https://allyhub.com/docs/reference/sdk/footage.md)) |
| `ctx.texts(t)` | The text of the layers listed before this one at `t`: `[{ layer, text, box }]`. It draws them to measure, so call it in `mount` |
| `ctx.covered` | The format's covered areas, `[x, y, w, h]` each in the frame's pixels; none for a custom format |
| `ctx.content` | The content box, `[x, y, w, h]` ([below](#the-content-box)) |
| `ctx.wait(promise)` | Work that must finish before anything is drawn (a scenery's build). A rejection is reported with the layer, under its `code` if it carries a rule's, else AK-R001; work that does not settle within `seekLimit` is AK-P003 |
| `ctx.report?.({ code, message, level? })` | Reports what went wrong drawing this layer, at any moment; a code that is not a rule's is AK-R001 |
| `ctx.film?` | The video on its clock: `start` (the part's start, film seconds), `part` (its key), `at(ref)` (film seconds of an anchor of any part, or a part's key), `outer` (where an outer video shows this one). Reading it makes the part's place in the film part of its identity |
| `ctx.video?.(piece, el)` | Another video item drawn in an element of this layer's ([below](#a-video-inside-a-layer)) |
| `ctx.embedded` | True in a video drawn inside another |
| `ctx.layoutOnly` | True while a moment is drawn only to measure its layout: nothing reads its pixels. A layer that paints a canvas no layout depends on may skip painting then; it still places its elements |
| `ctx.realTimers?` | The page's own clock and timers (`now`, `setTimeout`, `clearTimeout`), for work that waits on the wall clock (a loader, a worker), never for what a frame shows |

### The content box

`layout(ctx, opts?)` gives `{ W, H, k, orient, pad, top, bottom, left, right }`; `ctx.content` is the same box as `[x, y, w, h]`. In pixels:

```
k      = min(W, H) / 1080              the type scale: 1 in every preset
margin = 120 × k (landscape), 84 × k (portrait, square)
pad    = max(margin, safe.left, safe.right)
top    = max(pad, safe.top + 30 × k)
bottom = H − max(pad, safe.bottom + 20 × k)
left   = pad,  right = W − pad
```

`right` and `bottom` are coordinates, not widths. `layout(ctx, { margin, topGap, bottomGap })` changes the margin and the gaps.

### A video inside a layer

`await ctx.video(piece, el)` draws another video item of the project (the piece this module imported) inside `el`, in its own format and, where it has it, this video's language. It gives `{ id, duration, width, height, seek(t), at(ref) }`: `seek(t)` draws its moment `t`, `at(ref)` finds its own anchor or part's key in its seconds. It draws its graphic layers over its background; what it reads counts as this video's. A chain of videos that reaches itself is AK-M010. Put it behind `ctx.wait`. More in [footage.md](https://allyhub.com/docs/reference/sdk/footage.md).

## `@allyhub/sdk/dom`

| Helper | What it does |
| --- | --- |
| `h(tag, style?, children?, cls?)` | An element with styles and children; a string child is a text node |
| `css(el, style)` | Sets styles: camelCase or `--custom` names; a number gets `px`, except `opacity`, `zIndex`, `fontWeight`, `lineHeight`, `flex`, `flexGrow`, `flexShrink` |
| `layout(ctx, opts?)`, `contentBox(L, style?)` | The content box ([above](#the-content-box)); an absolutely placed flex column over it |
| `tag(el, name)`, `one(el, name)`, `all(el, name)` | Names an element (`data-ak`); finds the first, or every one, again. The measurements (`allyhub inspect`) name what they follow by it |
| `text(v)`, `list(v)` | A prop as a string; as a list of strings |
| `textBlock(value, { size, weight?, color?, font?, lineHeight?, align? })` | A `div` of balanced, wrapping text, Chinese broken only between words. Defaults 700, `var(--ak-color-fg)`, `var(--ak-font-display)`, 1.15, `"left"` |
| `wordBreaks(value)` | Chinese text with zero-width spaces between its words, for `word-break: keep-all` |
| `marked(line, styles?)` | A `span` of a line with its marks drawn (`**strong**`, `*em*`, `~~struck~~`, `` `code` ``): each marked run a span with `data-mark` and the style of its kinds, `styles` over `MARK_STYLES` (`strong` 700, `em` the accent colour, `strike` a line through, `code` the mono font at 0.9 em) |
| `fitTo(el, { min, max, maxHeight })` | The largest font size at which `el` fits its width and `maxHeight`; sets it |
| `fitLines(el \| text, { lines, min, max, width?, height?, precision? })` | `{ size, fits, lines }`: the largest size at which the text takes at most `lines` lines of the box (a text also takes `style`, and needs `width`). Also from `@allyhub/sdk` |
| `textLines(el)` | Each line of `el`'s text as the browser broke it. Also from `@allyhub/sdk` |
| `freeAreas(ctx, t, opts?)` | The bands of the content box at `t` clear of faces, other layers' text and covered areas, tallest first. Call it in `mount` |
| `captionTop(ctx, L, cue, w, h, opts?)` | A top for a block `w × h` over one cue: the first spot of `prefer` (default bottom, top, middle) clear of faces and other text. Call it in `mount` |
| `emphasized(words, list)`, `wordEmoji(words, map)` | Per word of a caption cue: whether `list` names it; the emoji `map` gives it |
| `emojiEl(value, style?)` | A span for an emoji in `var(--ak-font-emoji)` |
| `lightDark(el)` | The look's background and text colours as `{ light, dark }`. Call it in `mount` |

Nothing places, stresses or decorates on its own: these are measurements and builders a layer calls.

## Animation, text, paths and noise

From `@allyhub/sdk`; pure functions.

| Function | What it does |
| --- | --- |
| `tween(t, { from?, to?, start?, dur?, ease? })` | The value at `t`; defaults 0, 1, 0, 0.5, `ease.out` |
| `progress(t, start, dur)`, `lerp(a, b, x)`, `clamp(x, lo?, hi?)` | 0 → 1 over a span, clamped; interpolation; clamping (default 0 to 1) |
| `ease.linear`, `in`, `out`, `inOut`, `outExpo`, `outBack`, `spring(damping?, frequency?)` | Curves 0 → 1 (cubic `in`, `out`, `inOut`; `spring` defaults 7, 3.2). Any `(x) => number` is an `Ease` |
| `stagger(i, gap)` | `i × gap` |
| `rand(seed)` | A seeded random number generator: the same seed, the same numbers |
| `fitText(el, { min, max })` | The largest font size at which `el`'s text fits its own box; sets it |
| `splitText(text, by?)` | `"words"` (default), `"chars"`, or a separator |
| `countText(value, x, from?)` | `"$1,200.5M"` counting: its number `x` (0 → 1) of the way from `from`, keeping what is round it, its decimals and separators |
| `readMarks(line)`, `markRuns(text, marks)`, `withoutMarks(line)` | A line's marks read into its text and `InlineMark`s; as runs; the line without them |
| `pathLength(d)`, `pointAtLength(d, l)`, `tangentAtLength(d, l)` | An SVG path measured without the browser |
| `drawOn(d, progress)` | `{ strokeDasharray, strokeDashoffset }` showing the first `progress` of a stroke |
| `trimPath(d, from, to)`, `interpolatePath(a, b, x)`, `normalizePath(d)` | A stretch of a path (fractions of its length); the path between two with the same commands (it throws otherwise); absolute commands |
| `routeConnections(boxes, connections, { margin?, bend?, spread?, cross?, bounds? })` | Routes at right angles from a side of one box to a side of another, round every other box: an orthogonal grid round the boxes grown by `margin` (default 16), the cheapest way with each bend costed as `bend` of length (48) and each crossing of another line as `cross` (120), each line then routed again round the others while that crosses fewer (rip-up and reroute), lines sharing a channel set `spread` apart (8) in the order that crosses fewest (each pair followed on to where it parts, and set on the side it turns to there); within `bounds` when given; each route's corners and the sides it uses (`ROUTE_DEFAULTS`). Crossings left are the boxes' placement's: `routeCrossings(routes)` counts them |
| `noise2D(seed, x, y)`, `noise3D(seed, x, y, z)`, `noise4D(seed, x, y, z, w)` | Seeded simplex noise in [−1, 1], changing over about one unit |

## A person's input

A mouse's cursor, a hand (a finger hovering a screen, or a thing held to it), a finger's tap, a drag, a scrolled list or a field typed into, as functions of time. They place nothing: the piece says where and when, and draws what they return. Defaults: `INPUT_DEFAULTS` ([defaults.md](https://allyhub.com/docs/reference/sdk/defaults.md)).

- **A cursor** glides: an aimed movement timed by Fitts' law, landing exactly where it is aimed, with none of a hand's errors; it rests before a click and after it. A hand's errors are options (`overshoot`, `scatter`, `bow`, `tremor`), none by default.
- **A hand** errs as hands do: past its target and back, a little off, its path bowed, trembling, each move drawn differently by `seed` and `index`. For what a hand holds or touches.

| Function | Returns |
| --- | --- |
| `cursor({ from, steps: [{ at, to, size?, press?, duration?, dwell?, hold?, after? }], dwell?, hold?, after?, …reach })` | `{ at(t) → { x, y, down }, moves, presses }` |
| `handPath({ from, steps: [{ at, to, size?, press?, duration?, dwell?, hold? }], dwell?, hold?, …reach })` | The same, moved by a hand |
| `reach(from, to, { end, duration?, size?, index? }, reach?)` | One movement: `{ start, end, from, to, at(t), progress(u), bow }` |
| `tap({ at, to, hold?, slide?, grow?, size?, scatter?, seed?, index? })` | A finger's: `{ down, up, at(t) → { x, y, down, contact } }` |
| `drag({ by?, from, to, at, duration?, size?, settle?, release?, index?, …reach })` | `{ down, start, end, up, to, at(t) → { x, y, down } }`: `by: "mouse"` (default) glides and holds still while down, `"finger"` moves as a hand and trembles |
| `scroll({ at, by, kind?, limit?, wheel?, flick?, seed?, index? })` | `{ start, end, at(t) → px }`: `"flick"` (default) with momentum, or `"wheel"` notches |
| `typing(text, { at, cps?, spread?, word?, mark?, think?, mistakes?, notice?, backspace?, seed? })` | `{ keys, times, end, text(t) }`; `mistakes: [{ at, typed }]` types one and corrects it (none unless asked) |
| `fittsTime(distance, size, fitts?)` | `a + b · log2(1 + distance / size)` seconds |
| `aimed({ overshoot?, peak?, primary?, vary?, seed?, index? })` | An aimed movement's progress as an ease, 0 → 1 |

The reach options are `overshoot`, `peak`, `vary`, `fitts: { a, b }`, `scatter`, `jitter`, `bow`, `tremor: { px, frequency }` and `seed`.

A cursor on an interface the piece draws is best `uiDemo`'s (below): it finds each element where it is when it is acted on. A cursor of a layer's own goes to the points the piece gives it:

```ts

const path = cursor({
  from: [200, 900],
  steps: [
    { at: 1, to: [960, 540], size: 120, press: true },
    { at: 2.4, to: [1400, 300] },
  ],
});

  mount(el) {
    el.append(
      tag(
        h("div", {
          position: "absolute",
          width: 24,
          height: 24,
          borderRadius: 12,
          background: "var(--ak-color-fg)",
        }),
        "cursor",
      ),
    );
  },
  render(el, t) {
    const dot = one(el, "cursor");
    if (!dot) return;
    const p = path.at(t);
    dot.style.transform = `translate(${String(p.x - 12)}px, ${String(p.y - 12)}px) scale(${p.down ? "0.8" : "1"})`;
  },
});
```

## Starter components

The SDK has no components of its own. `allyhub add component/<name>` (`component/caption-line`) copies a starter component's source into the project's `components/`, where it is the project's code; `allyhub add` alone lists them. Each documents its props in its source, every value a prop with a default (its `*_DEFAULTS` constant where it has one): read it after adding. Import it by a relative path. Only mechanisms are provided, never a layout: a title, a list or an end card is the piece's own `custom()` or component.

| Component | What it does |
| --- | --- |
| `uiDemo` (and `screenDemo`, same file) | A product's interface acted on: `uiDemo` draws it from the project's own UI components (`build(page)`), `screenDemo` from a screenshot with its elements file (`allyhub frames web`). Each step names what it acts on (a CSS selector in the page), found where it is at that moment: the camera goes in on it, the cursor lands inside it (`cursor.aim`, a share of its box) and clicks, types into it or presses it |
| `codePanel` | Code, data or a terminal in a panel: coloured, typed or revealed, lines and spans highlighted in time |
| `callout` | Marks places, labels them and draws lines between them. A place is another layer's element (a CSS selector), measured every frame, so a mark stays on it through a change of layout or a camera move. `fit: "text"` pads from the text as it reads (capitals' tops to baseline, ink to ink), so equal pads look equal |
| `connector` | Lines between named elements (CSS selectors of the frame's other layers) at right angles, round every other box and what `avoid` names, an arrow at the end; lines sharing a channel set apart. `allyhub inspect pages` reports how many times its lines cross. List it last in a component's `layers` |
| `chart` | Bars, horizontal bars, a line or a ring, with its scale, labels fitted and the draw-on |
| `captionWord`, `captionLine`, `captionSubtitle` | Captions from `ctx.captions()`: a word at a time; a line with the word being said marked; a quiet subtitle |
