# Surfaces

A surface is a named HTML document displayed on at most one rectangle of
terminal cells. Document content and screen placement are sent separately:
`a=doc` sets the document, and `a=place` assigns its **placement**. This
page explains how surfaces work; see the
[protocol](https://hotty.neuroplast.io/docs/protocol#5-surfaces) for the full rules (§5).

```text
program → ESC ] 7279 ; a=doc:s=card ; <h1>Deploy</h1><p id=status>Waiting</p> ST
program → ESC ] 7279 ; a=place:s=card:c=40:r=auto:n=1 ST
host    → ESC ] 7279 ; a=ok:n=1:s=card:re=place:c=40:r=3 ST
```

(Payloads are shown decoded here; on the wire they are base64-encoded.)

## A name and a document

A surface name identifies the surface in all subsequent commands. Names are
1 to 64 characters consisting of letters, digits, `_`, and `-`
([§3.5](https://hotty.neuroplast.io/docs/protocol#35-common-keys)). Because multiple runs of a program
in the same terminal could collide on short names, an SDK's `Surface(name)`
prefixes the name with the program name and PID, or with an environment-set
prefix ([SDK design](https://hotty.neuroplast.io/docs/sdk-design#41-terminal)).

`a=doc` creates a surface or replaces its entire document
([§5.1](https://hotty.neuroplast.io/docs/protocol#51-documents-adoc)). The payload can be a full HTML
document or a fragment, parsed according to standard HTML parsing rules.
Replacing a document preserves its existing placement and dimensions, so you
can swap a card's contents without re-placing it.

Two keys on `a=doc` are scoped to the document: `d=1` creates the surface
detached ([Detaching](#detaching)), and `scroll` enables internal scrolling
([Scrolling inside a document](#scrolling-inside-a-document)). Sending a new
`a=doc` without these keys resets both properties to their defaults.

To modify part of an existing document, send a delta instead of replacing the
whole document ([Updates](https://hotty.neuroplast.io/docs/concepts/updates)).

## A size in cells

Placement dimensions are specified in cells: `c` columns and `r` rows, each
between 1 and 1000 ([§5.2](https://hotty.neuroplast.io/docs/protocol#52-placement-aplace)). The host
converts those cell dimensions to CSS pixels for layout
([§5.3](https://hotty.neuroplast.io/docs/protocol#53-geometry)). Media queries and viewport units are
evaluated against the surface's dimensions, so `100vw` equals the surface's
width rather than the terminal window's width.

Setting `r=auto` (or omitting `r`) sizes the surface to fit its content, up
to 1000 rows. Include a sequence number `n` on the placement command to
receive the chosen row count in the host's reply.

Pixel rendering inside the rectangle may vary across hosts—just as text
varies across fonts—but the occupied cell footprint is exact (§5.3). The
terminal's grid alignment is preserved regardless of what the host renders
inside the surface.

## When the content changes height

A document's required height can change after placement: an image loads, a
font arrives, a delta appends content, or a terminal font change alters cell
dimensions (§5.2). The host does not resize the placement automatically,
because the cells below it belong to your program.

Setting `f=1` on a placement subscribes to `fit` events whenever the
document's required row count changes. The event payload reports the row
count that `r=auto` would currently select:

```text
program → ESC ] 7279 ; a=place:s=log:c=60:r=auto:f=1:n=2 ST
host    → ESC ] 7279 ; a=ok:n=2:s=log:re=place:c=60:r=4 ST
program → ESC ] 7279 ; a=delta:s=log:q=2 ; {"ops": [{"op": "append", "t": "lines", "v": "<li>tests passed</li>"}]} ST
host    → ESC ] 7279 ; a=ev:s=log:e=fit ; {"r": 5} ST
```

The program can then re-place the surface at 5 rows when layout space is
available. `fit` is opt-in so programs that use fixed-height surfaces do not
receive unnecessary events ([Appendix B](https://hotty.neuroplast.io/docs/protocol#appendix-b-rationale)).

## Windows

A placement can display a cropped region of its surface, called a **window**
(§5.2). `x` and `y` specify the window's top-left offset within the surface
(in columns and rows), and `w` and `h` specify its visible width and height.
When omitted, the entire surface is shown.

The surface is still laid out at its full `c` by `r` dimensions, but only
the windowed region is rendered and receives pointer events (§5.3). Changing
the window on an existing surface does not trigger a re-layout and should be
cheap for the host.

Windows are designed for full-screen applications that scroll layouts
containing surfaces, such as a transcript view. A surface partially scrolled
off the edge of a viewport displays only its visible slice, similar to
partial placements in the kitty graphics protocol:

```text
program → ESC ] 7279 ; a=place:s=diff:c=60:r=10:y=4:h=6 ST
```

Here, a 10-row diff has its top 4 rows scrolled out of view; the placement
renders the remaining 6 rows.

## Stacking

`z` controls the stacking order of overlapping placements, analogous to CSS
`z-index` (§5.2). Valid values range from `-1000` to `1000`, defaulting to
`0`. When two placements share the same `z`, the more recently created
surface appears on top.

- `z` is scoped to the placement: re-placing a surface without `z` resets it
  to `0`.
- All placements render above terminal cells regardless of `z`, except for
  backdrops ([below](#backdrops)).
- Where placements overlap, pointer events go to the topmost placement under
  the cursor.

## Backdrops

> [!NOTE]
> New in 0.6.

A placement with `b=1` is a **backdrop**: the host renders it behind the
terminal cells rather than in front of them
([§5.2](https://hotty.neuroplast.io/docs/protocol#52-placement-aplace)). Cells with the default
background are transparent to the backdrop, while cells with explicit
backgrounds, text, and the cursor render over it. A multiplexer, for example,
can render pane cards on a canvas backdrop while keeping terminal text in
the normal cell grid:

```text
program → ESC 7  ESC [ 1 ; 1 H  ESC ] 7279 ; a=place:s=canvas:c=80:r=24:b=1:C=1 ST  ESC 8
```

- **Check `features` first.** Only hosts that advertise `backdrop` support
  this mode. Other hosts ignore `b` and draw the surface above the cells,
  covering the text. Without the feature, fall back to cell-based borders
  and gutters ([Degrading](https://hotty.neuroplast.io/docs/concepts/degrading#features)).
- **Layering:** Backdrops render beneath terminal cells and all normal
  placements. Among multiple backdrops, `z` controls stacking order.
- **Placement-scoped:** Like `z`, `b=1` applies only to the current
  placement. Re-placing without `b=1` moves the surface back above the
  cells; hiding clears the backdrop state until the next placement.
- **No input.** Pointer events pass to the cells or surfaces above the
  backdrop, so `p` and `v` subscriptions receive nothing. Backdrops cannot
  hold keyboard focus: `a=focus` returns `EINVAL`, and placing a focused
  surface as a backdrop releases focus.
- **Full-bleed edges.** When a backdrop touches a screen edge, the host
  extends it across the window's outer padding so a full-screen canvas fills
  the entire window.
- **Update with deltas.** When a pane moves, splits, or changes focus, send
  a delta to update the backdrop's card position or focus ring
  ([Updates](https://hotty.neuroplast.io/docs/concepts/updates)).

## Where a placement goes

A placement's top-left corner starts at the current cursor cell (§5.2). By
default, the host advances the cursor to column 1 of the line immediately
below the placement, scrolling the screen if needed. A CLI tool can
therefore print a card at the cursor and continue writing normal output
directly beneath it.

Full-screen applications typically place surfaces at fixed coordinates using
`C=1`, which leaves the cursor position unchanged. Save the cursor, move to
the target cell, place with `C=1`, and restore the cursor:

```text
program → ESC 7  ESC [ 3 ; 5 H  ESC ] 7279 ; a=place:s=chart:c=40:r=12:C=1 ST  ESC 8
```

`ESC 7` saves the cursor, `ESC [ 3 ; 5 H` moves to row 3, column 5, and
`ESC 8` restores it. SDKs wrap this pattern as `PlaceAt`.

Placing an already-placed surface moves it and removes its previous
placement. Full-screen programs re-place surfaces whenever their layout
shifts during a redraw.

Placements also configure event subscriptions: `p` for pointer presses, `f`
for `fit`, and `v` for hover. These flags persist on the surface until
changed, so a program that re-places a surface every frame only needs to set
them once ([Input](https://hotty.neuroplast.io/docs/concepts/input#what-asks-for-each-event)).

## Scrolling inside a document

By default, surfaces do not scroll internally (§5.3). Overflowing content is
clipped, no scrollbars are shown, and scroll offsets remain at zero. Mouse
wheel events over the surface pass through to the terminal—scrolling
scrollback on the primary screen, or reporting wheel input to the program on
the alternate screen.

This lets a full-screen application manage scrolling uniformly across cells
and surfaces: it handles wheel events itself and re-places partially visible
surfaces using windows.

When a document is too large to lay out at full height—such as a long log
panel next to a form—paging through windows requires a round trip per scroll
step. Instead, enable native host scrolling with the `scroll` key on
`a=doc`:

```text
program → ESC ] 7279 ; a=doc:s=log:scroll=1 ; <pre>…</pre> ST
```

`scroll` is a bitmask of scrollable axes: `1` for vertical, `2` for
horizontal, and `3` for both. Along enabled axes, scrolling behaves like a
web page:

- The document root and any element with `overflow: auto` or
  `overflow: scroll` scroll overflowing content with host-rendered
  scrollbars.
- Users can scroll via mouse wheel, touchpad, touch drag, or keyboard while
  the surface holds keyboard focus ([Keyboard and focus](https://hotty.neuroplast.io/docs/concepts/keyboard)).
- Scroll gestures target the innermost scrollable element that can move in
  that direction, chaining outward to ancestors and eventually to the
  terminal unless stopped by `overscroll-behavior`.
- An element with `wheel` in `data-on` takes the wheel itself, and nothing
  scrolls over it ([Pointers and touch](https://hotty.neuroplast.io/docs/concepts/pointers#the-wheel)).
- A host may bounce a touchpad's or a finger's scroll at an edge and let a
  fling coast, as on a phone; the program hears nothing of the bounce
  ([Pointers and touch](https://hotty.neuroplast.io/docs/concepts/pointers#bounce-and-coast)).

Scrollbars occupy pixels inside the surface rectangle rather than extra
terminal cells, preserving the cell footprint. Standard CSS properties
(`scrollbar-width`, `scrollbar-color`, and `scrollbar-gutter`) control their
appearance.

Scrolls settle according to CSS Scroll Snap rules (new in 0.6) across
keyboard navigation, page jumps, wheel input, `reveal`, and `scroll` ops.
Because host scroll increments are not tied to terminal rows, use scroll
snapping to keep list items aligned to the top edge:

```css
ul { overflow: auto; scroll-snap-type: y mandatory; }
li { height: var(--hotty-cell-h); scroll-snap-align: start; }
```

Scrolling is handled locally in the host. The program is notified only when
observed elements enter or leave the viewport
([§9.5](https://hotty.neuroplast.io/docs/protocol#95-view)). Programmatic scrolling happens via focus
changes, `reveal`, or the `scroll` delta op (new in 0.8), which moves by the
host's standard scroll step ([Updates](https://hotty.neuroplast.io/docs/concepts/updates#the-ops)). Deltas preserve
current scroll offsets; replacing the document with `a=doc` resets scroll
position to the top left.

## Lifetime

A placement's lifetime matches the kitty graphics protocol: it is anchored
to the line where it was placed ([§5.4](https://hotty.neuroplast.io/docs/protocol#54-lifetime)). It
scrolls up with that line and is removed when the line drops off the
scrollback buffer. The underlying document remains in memory and can be
placed again.

- **Alternate screen:** Placements on the alternate screen are removed when
  leaving it, and the host should delete those surfaces as well.
- **Full reset (RIS):** Deletes all surfaces.
- **Multiplexers:** A passthrough multiplexer should delete surfaces left
  behind when a pane's program exits, matching a pane reset. If the
  multiplexer preserves the pane's screen output, it preserves detached
  surfaces alongside it.

Programs can also remove placements or surfaces explicitly:

| command | removes |
| --- | --- |
| `a=hide:s=<name>` | the placement; the document stays, with what the user did in it |
| `a=del:s=<name>` | the surface and its placement |
| `a=del:id=<id>` | a resource ([Images and the network](https://hotty.neuroplast.io/docs/concepts/resources)) |
| `a=del` | every surface |

Hide surfaces you plan to redisplay soon (such as a card scrolled out of
view), and delete surfaces you no longer need. Hidden surfaces still accept
deltas and render their updated state when placed again without resending
the document. Note that hidden surfaces still count toward host resource
limits ([§13](https://hotty.neuroplast.io/docs/protocol#13-limits)).

Hiding a focused surface returns keyboard focus to the terminal, equivalent
to `a=blur`. If `a=place` returns `ENOENT` (for example, after a terminal
reset), the host no longer has that surface; resend the document with
`a=doc`.

## Detaching

A surface is owned by the program that created it
([§5.5](https://hotty.neuroplast.io/docs/protocol#55-ownership-adetach)). Its events are written to that
program's input stream, and it acquires keyboard focus on that program's
behalf. The host cannot automatically detect when the program exits.

Because events go to whichever process is currently reading terminal input,
an un-detached surface left behind by an exited command will send click
events directly to the shell. Any program that leaves surfaces on screen
after exiting must **detach** them first, or create them detached:

```text
program → ESC ] 7279 ; a=doc:s=report:d=1 ; <table>…</table> ST
program → ESC ] 7279 ; a=place:s=report:c=60 ST
```

Use `d=1` on `a=doc` for display-only surfaces that never need input events,
even if you continue updating them with deltas. Use `a=detach:s=<name>` to
detach an interactive surface once you are done handling its input. Detached
state persists until the document is replaced by an `a=doc` without `d=1`.

A detached surface remains visible on screen and can still be placed,
hidden, updated with deltas, or deleted, and continues to scroll with its
line. However, it sends no input to the program:

- It emits no events of any kind.
- It cannot take keyboard focus (`a=focus` returns `EDETACHED`).
- Its form controls behave as `disabled` and match `:disabled`, while
  retaining any user-entered values.
- Local browser-like interactions continue to work: hover styles, text
  selection, `<details>` toggles, and terminal-handled hyperlinks.

Detaching a surface while the user is editing a field does not emit a
`change` event. To capture pending input before detaching, send `a=blur`
first: the field commits its value (emitting `change` if modified), followed
by `blur`. Detach once `blur` arrives.

A crashed program cannot detach its surfaces. A supervising process such as
a shell may detach them if it tracks their names; otherwise they remain
active until deleted or evicted from scrollback, similar to mouse reporting
left enabled after a crash ([Appendix B](https://hotty.neuroplast.io/docs/protocol#appendix-b-rationale)).
