# hotty-ts

hotty-ts is the TypeScript SDK for [hotty](https://hotty.neuroplast.io/docs),
HTML over the TTY, for Node and Bun. With it, a terminal program shows small
HTML documents, called surfaces, on rectangles of cells, and hears what the
user does in them. It follows the hotty repository's SDK.md: the same two
layers, names and defaults as the other SDKs, and every SDK section of the
conformance vectors.

It speaks hotty 0.10 and 0.9 (SPEC §15): a host's replies and events carry
msgpack bodies (SPEC §3.3), its query lists the versions it speaks
(`a=q:n=1:v=0.9,0.10`, SPEC §4), and keys are named as myelin key names 0.1 names them (SPEC
§10.4): `ctrl+a`, `arrow_left`, `shift+g`, and `mod+s` in a binding. A
terminal that speaks neither, an 0.8 one included, is no host to it,
and the program draws in cells. Moving a program from 0.9 is CHANGES.md's
"Upgrading from 0.9" in the hotty repository, and SDK.md's Appendix I.

```
npm install @neuroplastio/hotty
```

The 0.10.x package line speaks hotty 0.10 and 0.9. This repository owns the patch number.

```ts
import { NoTerminalError, Terminal } from "@neuroplastio/hotty/terminal";

let t: Terminal;
try {
  t = Terminal.open("hello"); // the terminal (/dev/tty), whatever stdout is
} catch (e) {
  if (!(e instanceof NoTerminalError)) throw e;
  console.log("Hello."); // no terminal: a pipe, a cron job
  process.exit(0);
}
try {
  if (await t.detect()) {
    await t.lineStart(); // surfaces are placed at the cursor
    t.print("hello", "<p>Hello, <b>HTML</b> in the terminal.</p>", { cols: 40, rows: 1 });
    await t.fence(); // the host's replies, before the shell reads the terminal
  } else {
    console.log("Hello."); // a terminal that is not a host, or not of this version
  }
} finally {
  t.close();
}
```

Testing it needs no terminal:

```ts
import { Host } from "@neuroplastio/hotty/test";

const h = new Host();
await run(new Terminal({ input: h, output: h, name: "hello", size: () => h }));
h.surface("hello-hello")?.text(); // "Hello, HTML in the terminal."
```

## Entry points

| import | what it is | SDK.md |
| --- | --- | --- |
| `@neuroplastio/hotty` | the wire layer: builders (with the op builders `text`, `attr`, `varOp`, …, the menu's, `touch` and `setField`), `encode`, `Decoder`, `Scanner`, `Detector`, `Reply`, `Event`, `Caps`, `unpack` for msgpack, what a host or a relay reads of a program's commands (`deltaOf`, `menuOf`, `menuShowOf`, `menuLevelOf`, `menuFind`, `touchOf`), and keys: `parseKey`, `decodeKeys`, `Keymap`, `TERMINAL_KEYS`. Pure: no I/O, no dependencies | §3 |
| `@neuroplastio/hotty/field` | `Field`, a text field's value, caret and selection edited by SPEC §10.2's actions, for a program that draws its fields in cells | §4.6 |
| `@neuroplastio/hotty/terminal` | `Terminal`, for a program with a terminal: one that prints documents and exits, asks a question, or streams a chart | §4.1 |
| `@neuroplastio/hotty/session` | `Session`, for a UI framework's adapter: modes, layout, relayout, limits, messages | §4.3 |
| `@neuroplastio/hotty/link` | `Link`, what `Terminal` and `Session` stand on: for an environment that reads the terminal itself and hands over what it reads | §4.2 |
| `@neuroplastio/hotty/test` | `Host`, a hotty host that runs inside a test. Needs parse5 (an optional peer dependency) | §4.4 |

Only `@neuroplastio/hotty/test` has a dependency. The rest uses the runtime's
own modules (`node:fs`, `node:tty`, `node:zlib`), which Node and Bun both have,
and reads msgpack with its own decoder (below).

## Deltas, flags and menus

A frame's changes to a surface go out as one delta, a list of ops that the
host applies in order and shows as one (SPEC §6.1). The op builders make
the ops; the one-op helpers (`setText`, `setAttr`, `setVar`, `removeAttr`,
`morphTo`, `reveal`, `scroll`) stay for a single change:

```ts
import { delta, menu, menuHide, menuShow, text, varOp } from "@neuroplastio/hotty";

t.send(delta("app-bar", [varOp("fill", "p", 40), text("label", "40 of 100")]));
```

`scroll(surface, target, action)` takes one of the host's steps for a scroll
action such as `scroll-down` or `scroll-end`, from the target outward, or
the root when the target is empty (SPEC §6.1). It moves no focus. A count
is as many `scrollOp(target, action)` ops in one delta.

A program carrying something over a surface asks what its cell holds with
`hit(surface, c, r, options)` (SPEC §9.7). The cell counts from the surface's
top left, negative above it and to its left. It is answered by default,
with or without a request number. An ok reply's `hit` is `{ t, tx?, ty? }`:
the element a drag would name there (`t` empty for none), and its drop
steps where it has them. Other replies and bodies that do not decode leave
`reply.hit` undefined.

`press`, `fit` and `hover` of a placement are `true`, `false` or absent: they
belong to the surface (SPEC §5.2), and a placement that leaves them out
leaves them as they were. A `Session` sends each only when it changes.

`backdrop: true` places a surface under the cells, as a backdrop (`b=1`,
SPEC §5.2): the text and every cell with a background of its own cover it,
and it takes no pointer and never the keyboard. It belongs to the
placement, as `z` does, so a placement without it is above the cells. A
host without the feature ignores it and draws the surface over the text:
place one only where `caps.has("backdrop")`, and otherwise draw in cells.

A reply to a delta names the op that failed by its index (`reply.op`). A
program that can do things sends them as a menu tree (`menu`), shows the
level its keys reach (`menuShow(["space", "f"])`) and hides it (`menuHide`),
and a pick, from a multiplexer's palette or an agent, reaches it as a
`command` event with the item's `name`. A host asks of its capabilities `caps.has("menu")`, and of a
host's `caps` event `caps.merge(ev.changed())`; the `Terminal`, the `Link`
and the `Session` keep their `caps` current that way.

A program that drags a slider with the mouse in its cells names those cells
with `touch([{ c, r, w, h, drag: "x" }])`, so that a finger drags it too
(SPEC §9.6). The areas are the screen's cells, counted from 0, kept per
screen: it sends them again when what it drew moves, the size changes or it
switches screens, and `touch()` when it ends.

A program that completes what the user is typing changes the field in place
with `setField(surface, id, { rev, text, from, to })` (SPEC §6.4), rather than
swapping in a new element. `rev` is the one the last `input` or `change`
event carried (`ev.rev()`), and the other fields of a `FieldChange` are
`value`, `from`, `to`, `text`, `sel` (anchor and caret) and `checked`, each
sent only when given. Positions are bytes of the value's UTF-8, which
JavaScript's string indexes are not: convert from UTF-16. If the user got
there first the host answers `ESTALE` (it replies on error by default, `q=1`)
and the program waits for the next `input`. An `input` or `caret` event
(`data-on~=caret`) also carries the selection, `ev.sel()`.

## A framework's adapter

The `Session` never writes a frame, and owns no stream. With each frame, the
program says where its surfaces are, and the adapter writes what `flush`
returns in the same write as the frame's cells:

```ts
const s = new Session({ link: t, onMessage: (m) => program.send(m) }); // ready, event, error, ack, relayout, pong, input
s.detect();

// each frame:
s.layout([{ name: t.surface("chart"), rect: { x: 2, y: 3, w: 40, h: 10 }, doc: () => chartHtml() }]);
s.watch(cells); // the framework's output: erases and scrolls ask for a relayout
write("\x1b[?2026h" + cells + s.flush() + "\x1b[?2026l");

// on the way out:
write(s.close()); // deletes the surfaces it sent, and no one else's
```

A `relayout` asks for a frame: the screen was erased or scrolled under the
surfaces, or the host lost a document. With `lost`, the host lost documents
(a full reset, a host restarting behind a relay), and likely the resources
they refer to as well (SPEC §2, §7.1), which only the program knows. The
program sends them again before the frame's `layout`, so that they reach the
host ahead of the documents; sending one again replaces it. One loss is told
once, however many documents it took.

```ts
// in onMessage:
if (m.kind === "relayout") {
  if (m.lost) s.send(res("app-css", "text/css", css)); // ahead of the documents, which go with the frame
  draw();
}
```

Some environments parse their input themselves and hand over complete
sequences. OpenTUI is one: it may keep the DA1 answers for itself, and it
writes between its frames. For those, the `Session` stands on a `Link`
instead of a `Terminal`. The adapter calls `link.osc(seq)` with each OSC,
which returns whether it was hotty's, and `link.da1()` with a DA1 answer it
does not keep. Detection then decides on the reply to the query alone, and is
done 300 ms later. A byte stream goes to `link.bytes(chunk)`.

## Text fields in cells

A program that draws its fields in cells can give them the same keymap
as its surfaces. Put `TERMINAL_KEYS` in a wrapper's `data-keys-inner`. Use the
`input` or `multiline` reader to resolve the same bindings in cells.

```ts
import { TERMINAL_KEYS, decodeKeys, platformOf, resolve } from "@neuroplastio/hotty";
import { Field } from "@neuroplastio/hotty/field";

const html = `<form data-keys-inner="${TERMINAL_KEYS}"><input id=name></form>`;
const keys = resolve(platformOf(caps), "input", "", TERMINAL_KEYS);
const f = new Field();
for (const key of decodeKeys(read)) {
  const action = key === undefined ? undefined : keys.lookup(key);
  if (action === "submit") submit(f.value);
  else if (action && key !== undefined) {
    if (f.key(keys, key)) reportInput(f.value);
  } else onKey(key);
}
```

Draw the selection using `f.selection()`. Shift with a move extends it.
In a resolved field's keymap, `tab=program` gives Tab to the program.
`keys.program("tab")` reports whether that binding holds. Shift+Tab moves
focus back and Escape reaches the program.

`resolve(platform, reader, own, ...inner)` reads the wrapper bindings
from outermost to innermost and then the focused element's own
`data-keys`. Every reader ignores actions it cannot use. A binding to
`default` in the focused element's own keymap restores the host's
default behavior. `parseKeymap` reads either attribute, and a resolved
`selection` keymap's `lookup` reports only keys that copy the selection.

## Context menus and other buttons

Use `data-on="contextmenu"` for a context menu. Anchor the menu at `c()` and `r()` in
surface cells, or at the element's `area()` when the event comes from
the menu key. A host may deliver `context_menu` or `shift+f10` as a key.
Use the focused element for those keys. Send the menu document ahead of
time and place it at a higher `z` when it opens. Fit it to the grid and
give it the keyboard for type-ahead, arrow keys, Enter and Escape. Close
it on a pick, blur, Escape, scroll or resize (SDK.md §4.7).

Use `aux` for other mouse buttons and `rightbutton` to take the physical
secondary button. Both report `auxclick` on release over the opted-in
element. With `drag` they can also report a drag. Its `dragstart` carries
the button for the duration of that drag.

## Fingers, gestures and the wheel

Style for touch with CSS: `@media (pointer: coarse)` and `@media (hover:
none)` follow the device that draws the surface, and the program hears
nothing of them (SDK.md §4.8). What the program hears follows the input:

- **The kind of pointer.** `pointer()` on a click, press, contextmenu,
  dragstart, gesturestart and wheel is `POINTER_MOUSE`, `POINTER_PEN`,
  `POINTER_TOUCH` or a later kind as it came, and `""` from the keyboard;
  `pointerKind(k)` takes a kind as a program does, an unknown one as the
  mouse. A `pointer` event (`EVENT_POINTER`) says the user changed kinds,
  and `Session.pointer` and `Link.pointer` keep the last, `POINTER_MOUSE`
  until the first, for a program that draws its hints in cells.
- **A drag per finger.** Key a drag by `surface` and `finger()`, undefined
  for a mouse's or a pen's. A `dragend` with `cut()` was cut short: a
  whiteboard drops the stroke.
- **Gestures.** `data-on="gesture"` makes two fingers, or a touchpad's
  pinch, a `gesturestart`, `gesture` and `gestureend` (`EVENT_GESTURE_START`,
  …), whose `gesture()` is `{ c, r, x?, y?, scale, angle, fingers }`, the
  whole transform since the start.
- **The wheel.** `data-on="wheel"` takes the wheel over the element:
  `wheel()` is `{ dx, dy, c, r, x?, y?, precise }`, CSS pixels summed over a
  frame. Zoom on one that is not `precise` or holds `MOD_CTRL`, and pan on
  a `precise` one.

A whiteboard is `data-on="drag gesture wheel aux"` with `touch-action:
none`. A 0.9 host sends none of this: offer keys or controls to zoom and
pan there, and take an event with no kind as the mouse's.

A map that pans and zooms, with `<div id=map data-on="drag gesture wheel"
style="touch-action: none">`:

```ts
import { MOD_CTRL } from "@neuroplastio/hotty";

// in onMessage, for m.kind === "event":
const ev = m.event;
if (ev.kind === "wheel") {
  const w = ev.wheel()!;
  if (!w.precise || ev.mods() & MOD_CTRL) zoomAt(w.c, w.r, Math.pow(1.0015, -w.dy)); // notches, or a browser's pinch
  else panBy(w.dx * sensitivity, w.dy * sensitivity); // a touchpad's two fingers
} else if (ev.kind === "gesturestart") {
  start = view; // each gesture carries the whole transform since its start
} else if (ev.kind === "gesture" || ev.kind === "gestureend") {
  const g = ev.gesture()!;
  view = scaledAbout(start, g.scale, g.c, g.r);
}
```

The sensitivity is the app's own: a touchpad's two fingers feel slow at
1:1, so 2 is a good start.

Relays use the wire readers and builders to route commands and events.
SDK.md §4.5 covers relay behavior, including suppressing a wheel along
a relayed document's scroll axis where the downstream terminal would
convert it into keys.

## Examples

Each one shows its hotty part in the open, and each is tested against the
test host (`test/examples.test.ts`):

| example | what it shows |
| --- | --- |
| [`hello`](https://github.com/neuroplastio/hotty-ts/blob/main/examples/hello.ts) | open, detect, `lineStart`, `print`, `fence`: the smallest program |
| [`progress`](https://github.com/neuroplastio/hotty-ts/blob/main/examples/progress.ts) | a bar moved by one delta of `varOp` and `text` ops; three renditions: surface, cells, pipe |
| [`ask`](https://github.com/neuroplastio/hotty-ts/blob/main/examples/ask.ts) | a form that takes the keyboard and reports a submit, then a detached summary in its place |
| [`board`](https://github.com/neuroplastio/hotty-ts/blob/main/examples/board.ts) | a full-screen program on a `Session` under its own renderer: layout, deltas, relayout, clicks and keys |

```
node examples/hello.ts      # or: bun examples/hello.ts
```

The SDK holds protocol tools only. Markdown, highlighting, charts and
document models are the program's, as SDK.md §1 has it.

## Names and choices

The names are Appendix A's TypeScript column: `placeAt`, `setText`, `reveal`,
`delRes`, `del` (`delete` is a reserved word), `fitRows`, `cellCss`, and on
`Event` `view()`, and on `Caps` `has(feature)`. The op builders are `morph`,
`inner`, `replace`, `append`, `prepend`, `before`, `after`, `remove`, `attr`,
`unattr`, `text`, `varOp`, `revealOp` and `scrollOp`; a `FieldChange` is `{ rev, value, from, to, text, sel, checked }`, each but `rev` optional; an `Op` is `{ op, target, key,
value }`, a menu is `{ label, items }` of `{ key, label, name, enabled,
items }`, and a touch area `{ c, r, w, h, drag }`. Options are
objects: `doc(s, html, { detached: true, q: 0 })`, `place(s, { cols, rows,
keepCursor })`.

- **Absence** is `undefined`: a reply's `code` and `op`, an event's
  `fields()`, a `Caps` field the host left out. A submit's `fields()` are
  pairs, `[name, value][]`; `mods()` is the modifier bits (`MOD_SHIFT`, …).
  An `auxclick` carries the DOM number in `button()` when present, and
  a `dragstart` uses `BUTTON_PRIMARY` when the detail omits it. A
  `contextmenu` exposes the pointer's cell through `c()` and `r()` when
  present. `finger()` is undefined where absent, `0` being the first
  finger; `cut()` is false where absent, and `pointer()` `""`.
- **Versions.** `VERSION` is `"0.10"` and `VERSIONS` is `["0.9", "0.10"]`.
  The query advertises both, lowest first. Detection accepts either.
  Read `caps.v` to tell the sessions apart: a 0.9 one hears no kind, no
  finger, no gesture and no wheel. `answerVersion(listed)` returns the
  highest shared version, compared as numbers (0.10 after 0.9), or
  `undefined` for `EVERSION`. The test host negotiates both versions and
  sends each session its version's events (HOST.md §5).
- **Errors** are exceptions: `HottyError` (from `reply.err()`), and
  `NoAnswerError` when a request or a fence gets no answer in time, which
  carries the replies read so far. `NoTerminalError` when the process has no
  terminal, and `HostError` from the test host.
- **Messages** are discriminated unions on `kind`: the `Scanner`'s segments,
  the link's input, the `Session`'s messages.
- **Bodies.** A host's replies and events carry msgpack maps (SPEC §3.3),
  and `Reply`, `Event` and `Caps` read each whole, every field it knows as
  its type. One that does not decode (an int field sent as `7.0`, a body
  cut short or nested more than 32 levels deep, or one that holds anywhere,
  in a field the SDK knows or not, what no host sends: a nil, a map key
  that is not a string or is given twice in one map, a string that is not
  UTF-8, an int further than 2^53 − 1 from zero, a timestamp of another
  size or out of range) leaves
  undefined what it would fill: `caps()`, an error's `code` and `detail`,
  `fields()`. The message stands.
- **msgpack** is read by the SDK's own decoder, not a package: JavaScript
  has one number type, and a reader of hotty's bodies keeps floats apart
  from ints. `unpack(bytes)` gives plain values, as an event's `detail` and a
  message's `body()` have them, and with `{ floats: true }` each float as a
  `Float`. A timestamp
  (extension −1) is a `Time`, seconds and nanoseconds since 1970, with
  `toDate()`; another extension is skipped. What fails a body fails
  `unpack` too, with a `SyntaxError`, as `JSON.parse` throws. The test host
  writes its bodies with a writer beside it, a float as one even when whole
  (`scale: 2.0`), and never a nil or a key that is not a string.
- **Escape.** A lone ESC at the end of a read is the Escape key once nothing
  follows it within 25 ms (`ESCAPE_DELAY`, the link's `escapeDelay`), so a
  sequence split between two reads is not taken for a key.
- **zlib** comes from the runtime's `node:zlib`. An environment without it
  gives the codec its own (`setZlib`).
- **Bun** cannot stop a blocking read of a terminal. So on Bun, `Terminal.open`
  reads stdin when stdin is the terminal, and otherwise polls /dev/tty
  without blocking, every 10 ms while it reads. Either way the process exits
  once the terminal is closed.
- **Windows** has no /dev/tty: `Terminal.open` throws `NoTerminalError`. A
  `Terminal` made from streams, the `Session` and the wire layer work
  anywhere.

## Conformance

The vectors are the hotty repository's `conformance/vectors.json`, of
version 0.10, copied to `test/testdata`, and checked against a checkout of
hotty when one is at hand (`HOTTY_DIR`, by default `../../hotty/main`).

- **SDK sections.** `wire`, `build`, `encode`, `decode`, `scan`, `detect`,
  `keys`, `keymap` and `edit` all run, and none is skipped: the runner
  declares every `requires`. Characters are grapheme clusters, from
  `Intl.Segmenter`, which Node and Bun both have (`graphemes`).
- **Host section.** The runner checks all host vectors whose `requires`
  it supports, including `speaks-0.9`, and its wheel steps; the touch and
  pinch vectors need a layout, and are skipped. Geometry fixtures supply pointer
  hits and measurements for placements that fit their contents.
  Use `Host.pointerDown`, `pointerMove` and `pointerUp` to test a held
  gesture. Supply the hit target and coordinates in surface cells.
  `Host.contextMenu` and `Host.auxClick` play single gestures, and
  `Host.setLinkArea` supplies geometry for a link without an id.
  `Host.usePointer(kind)` gives the kind of the presses that follow,
  `fingerDragStart`, `fingerDragMove` and `fingerDragEnd` drag with several
  fingers, each with its finger, `gestureStart`, `gestureMove` and
  `gestureEnd` play a gesture of fingers or a touchpad, and `wheel` turns
  the wheel by CSS pixels.
  The host keeps each control's `rev` and text selection, takes `a=field`
  and sends `caret`. Focus fixup keeps the keyboard on the surface and
  commits an edited field still in the document if its value changed.
  The test host estimates `r=auto` unless the test supplies an
  `autoRows` callback, and `hit` returns an empty target (SDK.md §4.4).
  An event's detail is compared each value of its type: the vectors' floats
  are read as `Float`s, as `unpack` gives a body's. A reply's `types` is
  checked by reading its body as that type, as `Reply` and `Caps` read one,
  and its `body` by unpacking it with its floats as `Float`s: each field it
  names, equal as a value.

## Development

The toolchain is in `mise.toml`: Node 26 and Bun.

```
make install   # npm ci
make check     # typecheck, build, the tests on Node and on Bun, the built package on both
make vectors   # copy the vectors from HOTTY_DIR
```

The sources are TypeScript that both runtimes run as they are (erasable
syntax only). `make build` writes the package's JavaScript and types to
`dist`.

## Licence

Apache-2.0.
