# Widgets

Elements the runtime builds and keeps itself: `editor`, `richtext`,
`terminal`, `flow`, `chart`, `htmlframe`.
Also where the other built-in elements are documented. Back to the
[map](README.md).

```mote
// docs: whole
state src = "let n = 1\n"
state saved = ""

action save(text: string)
  saved = text

column gap=8 padding=16
  editor value=src lang="js" change=save height=300
  text `${src.length} characters; ${saved.length} saved` color=dim
```

## Mental model

Most tags compile to plain DOM that the page's bindings drive. A **widget**
is different: it is a `<div>` that a part of the runtime fills and runs (a
textarea with coloured lines over it, a terminal's canvas, a pan-and-zoom
surface). The page talks to it through its attributes and events, and never
sees inside.

How it is wired (`compiler/src/tables.rs`, `widget`; `view.rs`, the widget
branch of `Gen::el`):

- Each widget names a runtime part (`ED`, `TM`, `FL`) and a list of its own
  attributes with their types.
- The page's expression for each attribute is handed over as a getter, so
  the widget follows state. Where the expression can be assigned (a state,
  or a path into one), a setter is handed over too, and the widget **writes
  back** (an editor's `value`, a flow's `zoom`).
- Every other attribute is an ordinary one on the `<div>`: styles, `id`,
  `aria-label`, and events. `focus`, `blur` and `key` on a widget are the
  keyboard anywhere inside it ([events.md](events.md#the-events)).
- A page that does not use a widget does not carry it.
- A widget draws in the page's colour roles, so it follows light and dark.

Size a widget with styles on the element (`height=300`, `flex=1`).

## The built-in elements, and where each is documented

| Element | What | Page |
|---|---|---|
| `editor` | a code editor | [below](#editor), [kit/editor.md](kit/editor.md) |
| `richtext` | a rich text editor, for mail and documents | [below](#richtext), [kit/richtext.md](kit/richtext.md) |
| `terminal` | a terminal emulator screen | [below](#terminal), [kit/terminal.md](kit/terminal.md) |
| `flow` | a canvas of nodes joined by edges | [below](#flow), [kit/flow.md](kit/flow.md) |
| `chart` | a chart drawn from the plot battery's numbers | [below](#chart), [charts.md](charts.md) |
| `htmlframe` | a letter's HTML cleaned and shown where nothing in it runs | [text.md](text.md#htmlframe) |
| `popover`, `tip` | panels that float beside an element | [markup.md](markup.md#popover-and-tip) |
| `dialog open=flag` | the browser's modal dialog | [markup.md](markup.md#binding) |
| `icon "name"` | a Lucide icon | [markup.md](markup.md#icons) |
| `image "file"` | a picture from `assets/` | [markup.md](markup.md#pictures-and-assets) |
| `camera` | the device's camera | [media.md](media.md#camera) |
| `reel` | a film playing | [media.md](media.md#reel) |
| `canvas layers=…` | layers of painted sheets | [media.md](media.md#canvas-layers) |
| `surface`, `surface gl` | a canvas your code draws on | [drawing.md](drawing.md) |
| `canvas boxes=…` | boxes in space | [drawing.md](drawing.md#the-3d-canvas-canvas-boxes) |
| `canvas scene=…` | meshes, lights and a camera | [scene.md](scene.md) |

The kit's components (`Button`, `Dialog`, `Markdown`, …) are Mote
components, not runtime elements: [kit.md](kit.md).

## editor

```mote
editor value=source lang="ts" lines wrap tab=2 readonly placeholder="…"
```

A code editor: a real `<textarea>` under coloured lines, so the caret,
selection, clipboard, IME, on-screen keyboards and undo are the platform's
own. It has pairs, indenting, comments (⌘/), find and replace (⌘F). The
colours come from the `syntax` battery in a worker ([text.md](text.md#syntax)).

| Attribute | Type | |
|---|---|---|
| `value` | string | The text. Written back on every edit when it is state. |
| `lang` | string | The language to colour as, and the comment style ([the list](text.md#code)). |
| `lines` | bool | The line-number gutter (on unless `lines=false`). |
| `wrap` | bool | Soft wrap. |
| `tab` | number | Spaces in one level of indentation (2). |
| `readonly` | bool | Selectable and searchable, not changeable. |
| `placeholder` | string | Shown, dim, while the text is empty. |

Events: `input` (every edit) and `change` (the editor is left with a
different text) hand the handler the text. With none of its styles set it
is 240px high.

Keys, find, what it shows and how it holds a long file:
[kit/editor.md](kit/editor.md). Source: `runtime/page/editor.mote`, part
`ED`.

## richtext

```mote
// docs: whole
state doc: json = richtext.from("Hello Ada,")
state sent = ""

action send
  sent = richtext.html(doc)

column gap=8 padding=16
  richtext value=doc placeholder="Write…" aria-label="Message" height=240
  button "Send" press=send
  text sent color=dim
```

A rich text editor, with a toolbar: bold, italic, code, links, headings,
lists, quotes, pictures. Its document is the page's value, a list of
blocks (`{blocks: [{id, kind, text, marks, …}]}`), not the DOM; mail is made
of it with `richtext.html` (inline styles only) and `richtext.text`, on
either side.

| Attribute | Type | |
|---|---|---|
| `value` | json | The document. Written back on every edit when it is state. |
| `pictures` | json | `{ref: address}`: where each picture of the document is shown from. |
| `placeholder` | string | Shown, dim, while the document is empty. |
| `readonly` | bool | Selectable, not changeable; no toolbar. |
| `toolbar` | bool | The toolbar (on unless `toolbar=false`). |
| `tools` | string | Its buttons: `"bold italic link \| heading bullet number quote \| picture"`. |

Events: `input` (every edit) and `change` (left with a different document)
hand the handler the document; `edit` hands it each edit's operations (to
apply elsewhere with `richtext.apply`); `picture` a picture put in as a
file, `{ref, name, type, data}`.

Keys, the document and its operations, mail of it, input methods, paste,
what a screen reader is told: [kit/richtext.md](kit/richtext.md). Source:
`runtime/page/richtext.mote`, part `RX`, and `runtime/shared/richtext.mote`,
part `RXM`.

## terminal

```mote
// docs: whole
state out = "Welcome\r\n$ "
state grid = ""

action typed(data: string)
  out += data

action sized(s: string)
  grid = s

column gap=8 padding=16
  terminal output=out input=typed change=sized height=320
  text grid color=dim
```

A terminal emulator screen: a VT parser, scrollback, a canvas renderer. It
is a screen, not a shell: the page gives it bytes to show and is handed the
bytes the user types.

| Attribute | Type | |
|---|---|---|
| `output` | string | The bytes to show. **Append to it**: when the new value starts with the old one, only the new part is written. Any other value is a reset. |
| `cols`, `rows` | number | The grid's size. Left out, the grid is fitted to the element. |
| `scrollback` | number | Lines kept above the screen (1000). |
| `cursor` | bool | Whether the cursor blinks (true). |

Events: `input` hands the handler the bytes a terminal would send (a key,
pasted text, a mouse report); `change` hands `"COLSxROWS"` when the fitted
grid has a new size.

A line feed only goes down, as on a real terminal: write `\r\n`. Mote
strings have no `\x1b`: write `String.fromCharCode(27)` for Escape.

Everything else (escape sequences, what keys send, selection, colours):
[kit/terminal.md](kit/terminal.md). Source: `runtime/page/terminal.mote`,
part `TM`.

## flow

```mote
// docs: whole
shape Step
  id: string
  x: number
  y: number
  title: string

shape Wire
  id: string
  from: string
  to: string

state nodes: Step[] = [{id: "a", x: 0, y: 0, title: "Start"}, {id: "b", x: 320, y: 80, title: "End"}]
state edges: Wire[] = [{id: "e1", from: "a", to: "b"}]
state locked = false

action changed(e: string)
  let ev: json = JSON.parse(e)
  if ev.type == "move"
    for m in ev.nodes
      let hit = nodes.find(s => s.id == m.id)
      if hit
        hit.x = m.x
        hit.y = m.y

flow edges=edges locked=locked change=changed height=400
  for s in nodes key=s.id
    view id=s.id data-x=s.x data-y=s.y padding=12 background=card border-radius=8
      text s.title
  view data-panel="top-right"
    button (locked ? "Unlock" : "Lock") press={locked = !locked}
```

A canvas of nodes joined by edges, panned and zoomed.

- **The nodes are the element's own children**, written by the page: any
  markup with `id`, `data-x`, `data-y` (canvas coordinates of its top left
  corner). `for` and `if` work on them as anywhere.
- A child with `data-panel="top-left"` (or `top-center`, `top-right`,
  `bottom-left`, `bottom-center`, `bottom-right`) stays put over the canvas.
  A child with `data-toolbar-for="nodeId"` floats beside that node.

| Attribute | Type | |
|---|---|---|
| `edges` | a list | Each `{id?, from, to, …}`; `from` and `to` are node ids. More fields (`kind`, `animated`, `dashed`, `label`, `color`, `arrow`, handles) in [kit/flow.md](kit/flow.md). |
| `zoom`, `x`, `y` | number | The view. Written back as the user pans and zooms, when they are state. |
| `locked` | bool | No dragging, connecting or removing. |

**One event, `change`**, handed a JSON string: `{type: "move", nodes: [{id,
x, y}]}`, `{type: "select", …}`, `{type: "connect", from, to, …}`,
`{type: "remove", nodes, edges}`, `{type: "view", x, y, zoom}`. Parse it:
`let ev: json = JSON.parse(e)`.

**Positions are the page's data.** During a drag the element moves the node
itself; at the end it says `move`, and from then on the node is wherever the
page's `data-x` / `data-y` say. A page that does not write the move down
gets the node back where it was. The same for `remove` and `connect`.

The kit's `Canvas`, `Node`, `Controls`, `Panel` and `Toolbar` are components
over it. Everything else (handles, selection, keys):
[kit/flow.md](kit/flow.md). Source: `runtime/page/flow.mote`, part `FL`.

## chart

The element under every chart of the kit ([charts.md](charts.md)): write the
kit's components; this is for one of your own.

```mote
// docs: whole
state rows: json = [{x: 1, y: 3}, {x: 2, y: 5}, {x: 3, y: 4}]
state seen = ""

action heard(e: string)
  let ev: json = JSON.parse(e)
  seen = ev.type

column gap=8 padding=16
  chart data=rows marks=[{kind: "line", y: "y", label: "y"}] x=({col: "x", type: "linear"}) label="A line" change=heard height=200
  text seen
```

| Attribute | Type | |
|---|---|---|
| `data` | any | rows, a record of columns, or a list of numbers |
| `marks` | a list | `{kind, y, …}` each; and the children that say `data-mark` |
| `kind` | text | `xy` (unsaid), `pie`, `polar`, `radial`, `gauge`, `radar`, `funnel`, `calendar`, `treemap`, `sunburst`, `sankey` |
| `x`, `y`, `y2` | records | `{col, type, domain, format, axis, …}` |
| `series`, `notes` | lists | names and colours of the series; words of the notes |
| `range`, `picked`, `hidden` | lists | the view, the brushed range, the series hidden: written back |
| `tooltip`, `legend`, `zoom`, `grid`, `format`, `zone`, `facet`, `label`, `sync` | text | |
| `crosshair`, `brush`, `download`, `flip`, `motion` | bool | |
| `window` | number | rows kept, newest last |

**One event, `change`**, handed a JSON string: `{type: "pick" | "brush" |
"range" | "legend", …}`. `el.chartMarks()` gives what it drew as a table.
Source: `runtime/page/chart.mote`, part `CH`.

## Pitfalls

- **A widget attribute is typed.** `tab="2"` is refused: `tab` is a number.
- **Give a widget a height.** A `flow` with no height is 160px; a
  `terminal` is as tall as its rows; an `editor` 240px.
- **Write-back needs state.** `editor value=(a + b)` shows the text and
  cannot write it; hear `input=` instead.
- **`terminal output` must grow by appending.** Replacing it resets the
  screen.
- **A `flow` forgets what the page does not keep.** Handle `move`,
  `connect` and `remove`, or they are undone.

## Where a new element goes

A new element the runtime builds gets a `##` heading here (what it is, its
attribute table, its events, a whole example), a row in the table of
built-in elements, and, when it is large, a page of its own under `kit/`.
How to add one to the compiler: [internals.md](internals.md#adding-a-widget).

## In the source

| What | Where |
|---|---|
| The widget table: part and typed attributes | `compiler/src/tables.rs`: `widget` |
| Getters, setters, the part's call | `compiler/src/view.rs`: `Gen::el` |
| Attribute types checked | `compiler/src/types.rs`: `Checker::el` |
| The editor | `runtime/page/editor.mote` |
| The terminal | `runtime/page/terminal.mote` |
| The flow canvas | `runtime/page/flow.mote` |
| The chart | `runtime/page/chart.mote`, with `batteries/plot` ([charts.md](charts.md#in-the-source)) |
| Recorded behaviour | `tests/kit_editor.real.mjs`, `tests/kit_terminal.real.mjs`, `tests/kit_flow.real.mjs`, `examples/kit/editor.mote`, `terminal.mote`, `flow.mote` |
