loom
Draw TML documents into terminal cells. Flex layout, theme roles at every colour depth, redraws of only what a patch changed, and local keys and clicks.
tuios.dev/loom draws TML documents. You give it a document and a size. It gives you a cell buffer, which renders to ANSI text or to plain text. Charts come from plot. tuios draws every TML surface with loom.
The API reference is on pkg.go.dev.
Quickstart
go get tuios.dev/loom tuios.dev/tmlpackage main
import (
"fmt"
"log"
"tuios.dev/loom"
"tuios.dev/tml"
)
const src = `<tml version="1">
<state>{"passed": 412, "failed": 3, "runs": [41, 39, 44, 40, 52, 47, 38, 45, 49, 43]}</state>
<col gap="1">
<row gap="3">
<stat label="passed" value="{state.passed}" role="success"/>
<stat label="failed" value="{state.failed}" role="error"/>
<spacer/>
<gauge value="{pct(state.passed, state.passed + state.failed)}" w="16" role="success"/>
</row>
<bar data="state.runs" title="Seconds per run" h="5"/>
</col>
</tml>`
func main() {
doc, problems, err := tml.Check([]byte(src), nil)
if err != nil {
log.Fatal(problems)
}
s, err := loom.New(doc, &loom.Options{Palette: loom.DefaultPalette(loom.TrueColor)})
if err != nil {
log.Fatal(err)
}
buf := s.Render(56, 7)
fmt.Println(buf.Render()) // ANSI text; buf.String() gives plain text
}The buffer belongs to the surface. The next Render reuses it. buf.Cell(x, y) gives one cell with its text, colours and attributes, for a host that composites cells itself.
The tml command
tml shows a TML document in the terminal, drawn by loom, without tuios. It needs Go 1.25 or newer:
go install tuios.dev/loom/cmd/tml@latestEach tuios release from v0.11.0 also carries a tml archive for Linux, macOS, Windows and FreeBSD, on x86_64 and arm64. Download it from the releases page, or install it with a package manager:
brew install --cask gaurav-gosain/tap/tuios-tml # macOS and Linux
yay -S tuios-tml-bin # Arch Linux, from the AURtml dashboard.tml # full screen, with keys and the mouse
tml report.tml --print --width 100 # draw once, as text
tml report.tml --check # print each problem in the document
answer=$(tml confirm.tml) # the value of close(), as JSON- In a terminal the document opens full screen. Press
qorescto quit when the document does not use the key, orctrl+cat any time. - A
closeaction quits, andtmlprints its value as JSON. Acopyaction copies with OSC 52.emit,open,paneand links need a host such as tuios, so they do nothing here. - When the output is not a terminal, or with
--print,tmldraws the document once and writes it as text. tml -hlists every flag.
Flex layout
Layout works like flex boxes for cells. A row places its children left to right, and a col top to bottom.
wandhtake cells, a percentage,fillorfill:N. Thefillboxes share the space that is left, by their weight N.min-w,max-w,min-handmax-hbound a size. Afillbox at its maximum gives the rest to the others.pad,gap,grow,alignandjustifywork as their names say.- A box never draws outside its parent. When a column is too short, tables, lists, text, cards and tabs give rows back first.
Wrap
A row that holds a button wraps when its children do not fit side by side. Whole buttons go to the next line, so no label is cut. A spacer goes with the child after it, so a hint at the right stays at the right.
<row gap="2">
<button key="r" kind="primary" on-press="emit('rerun')">Rerun failed</button>
<button key="o" on-press="emit('log')">Open log</button>
<button key="e" on-press="emit('edit')">Open in editor</button>
<button key="c" on-press="emit('copy')">Copy names</button>
<spacer/>
<text role="mute"><kbd>esc</kbd> close</text>
</row>Change the layout with the width
A binding can read view.width, view.height and view.band. The band is narrow below 72 cells, medium below 120 and wide from 120. Use it in an if to pick a layout.
<tml version="1">
<state>{"passed": 412, "failed": 3, "skipped": 9}</state>
<col gap="1">
<text role="mute">view.width = {view.width}, view.band = {view.band}</text>
<row gap="2" if="view.band == 'wide'">
<stat h="3" w="fill" label="passed" value="{state.passed}" role="success"/>
<stat h="3" w="fill" label="failed" value="{state.failed}" role="error"/>
<stat h="3" w="fill" label="skipped" value="{state.skipped}"/>
</row>
<row gap="3" if="view.band != 'wide'">
<stat label="passed" value="{state.passed}" role="success"/>
<stat label="failed" value="{state.failed}" role="error"/>
<stat label="skipped" value="{state.skipped}" if="view.band == 'medium'"/>
</row>
</col>
</tml>Colour depth
Every colour is a role, such as success, mute or series2. You give the surface a Palette at the depth of the terminal: TrueColor, Color256, Color16 or ASCII.
DefaultPalette(depth)gives the tuios palette at each depth. At 256 colours each colour is the nearest of the xterm 256, by distance in OKLab.NewPalette(depth, roles)builds a palette from your theme. A role you leave out takes a colour derived from the others. The pictures on these pages useNewPalettewith the colours of this site.- At 16 colours there are no grounds. The cursor row and a primary button use reverse video.
- In ASCII, loom draws its own marks in ASCII, and the charts use ASCII glyphs.
The same document with DefaultPalette at each depth. Click a picture to open it at full size.
Updates: the retained tree
A surface keeps its tree of boxes between frames. Nothing is laid out or drawn again unless something changed.
- A state patch marks only the boxes whose bindings read the changed paths.
- The next
Renderevaluates those boxes again, lays the tree out, and repaints only the boxes whose content or place changed. Damagereturns the rectangles repainted since its last call, including the renders that input caused. A host sends only those cells to the terminal.- A
Renderwith nothing changed does no work.
err := s.Patch(ops) // a JSON Patch from the owner
err = s.Set("state.cpu", 43) // or one value
buf := s.Render(80, 24)
for _, r := range s.Damage() {
// send the cells in r
}This picture is the dashboard after a patch in which a skipped test ran and passed: it sets /passed to 413 and /skipped to 8. The tinted cells are the rectangles Damage returned. The chart and the failures did not change, so loom did not draw them again.
On a 200-row table at 200 by 55 cells, a full render takes about 0.6 ms. The redraw after a patch to one binding takes about 15 µs. The tests hold both to a budget.
Keys and the mouse
Key and Mouse take input. Tabs, sorting, the cursor, folding, scrolling, set and toggle run at once, with no round trip to the owner. emit, close, copy, open and pane come back to your program as Effects.
- A button's
keyworks from anywhere on the surface. tabandshift+tabmove the focus.- The focused table or list takes the arrow keys,
enter, andsto sort by the next sortable column. The same column again flips the order. - A click opens a tab, sorts a column, moves the cursor, folds a card or presses a button. The wheel scrolls. A drag moves a split.
res, err := s.Key("r")
for _, e := range res.Effects {
if e.Action == "emit" {
send(e.Name, e.Value) // to the owner of the surface
}
}
res, err = s.Mouse(loom.Mouse{X: 25, Y: 0, Button: loom.MouseLeft, Action: loom.Press})A click on a link comes back as a link effect. Your program asks the person, then opens it. loom writes no OSC 8 link unless you set Options.Hyperlinks.
Embed loom in a Bubble Tea program
A complete Bubble Tea v2 program. It shows a document, sends keys, clicks and the wheel to the surface, and shows each event on the last line. The build of these docs compiles it.
// A Bubble Tea v2 program that shows a TML document with loom. Keys and
// clicks go to the surface. Its emit actions come back as effects.
package main
import (
_ "embed"
"fmt"
"log"
tea "charm.land/bubbletea/v2"
"tuios.dev/loom"
"tuios.dev/tml"
)
//go:embed dashboard.tml
var src []byte
type model struct {
s *loom.Surface
w, h int
status string
}
func (m model) Init() tea.Cmd { return nil }
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.w, m.h = msg.Width, msg.Height
case tea.KeyPressMsg:
switch msg.String() {
case "ctrl+c", "esc":
return m, tea.Quit
}
// loom names keys as Bubble Tea does: up, enter, shift+tab, r.
return m.handle(m.s.Key(msg.String()))
case tea.MouseClickMsg:
if msg.Button == tea.MouseLeft {
return m.handle(m.s.Mouse(loom.Mouse{X: msg.X, Y: msg.Y, Button: loom.MouseLeft, Action: loom.Press}))
}
case tea.MouseWheelMsg:
b := loom.WheelDown
if msg.Button == tea.MouseWheelUp {
b = loom.WheelUp
}
return m.handle(m.s.Mouse(loom.Mouse{X: msg.X, Y: msg.Y, Button: b, Action: loom.Press}))
}
return m, nil
}
// handle acts on what the surface sends back. Tabs, sorting, the cursor and
// set() already ran inside loom. The rest is for the program.
func (m model) handle(res loom.Result, err error) (tea.Model, tea.Cmd) {
if err != nil {
m.status = err.Error()
return m, nil
}
for _, e := range res.Effects {
switch e.Action {
case "close":
return m, tea.Quit
case "emit":
m.status = fmt.Sprintf("event %q: %v", e.Name, e.Value)
}
}
return m, nil
}
func (m model) View() tea.View {
v := tea.NewView("")
v.AltScreen = true
v.MouseMode = tea.MouseModeCellMotion
if m.w > 0 && m.h > 1 {
// Render does no work when nothing changed since the last frame.
v.SetContent(m.s.Render(m.w, m.h-1).Render() + "\n" + m.status)
}
return v
}
func main() {
doc, problems, err := tml.Check(src, nil)
if err != nil {
log.Fatal(problems)
}
s, err := loom.New(doc, &loom.Options{Palette: loom.DefaultPalette(loom.TrueColor)})
if err != nil {
log.Fatal(err)
}
if _, err := tea.NewProgram(model{s: s}).Run(); err != nil {
log.Fatal(err)
}
}<tml version="1" title="go test ./...">
<state>{"passed": 412, "failed": 3, "skipped": 9, "secs": [41,39,44,40,52,47,38], "failures": [
{"pkg": "internal/session", "test": "TestAttachRace", "ms": 2210},
{"pkg": "internal/app", "test": "TestDockClick", "ms": 840},
{"pkg": "vt", "test": "TestKittyPlaceholder", "ms": 120}]}</state>
<col gap="1" pad="1">
<row gap="3">
<stat label="passed" value="{state.passed}" role="success"/>
<stat label="failed" value="{state.failed}" role="error"/>
<stat label="skipped" value="{state.skipped}" role="dim"/>
<spacer/>
<gauge value="{pct(state.passed, state.passed + state.failed)}" w="14"/>
</row>
<bar data="state.secs" h="4" title="Seconds per run, last 7"/>
<card title="Failures" meta="{len(state.failures)}" role="error">
<table rows="state.failures" key="test" sort="ms:desc" select="single"
on-select="emit('open', event.row)">
<column field="pkg" title="Package" w="fill"/>
<column field="test" title="Test" w="fill:2"/>
<column field="ms" title="Time" align="right" format="dur(value, 'ms')"/>
</table>
</card>
<row gap="2">
<button key="r" on-press="emit('rerun', state.failures)">Rerun failed</button>
<button key="o" on-press="emit('log')">Open log</button>
<spacer/><text role="mute">esc close</text>
</row>
</col>
</tml>Press r and the last line shows the rerun event with the failed tests. The arrow keys move the cursor of the focused table, and tab moves the focus.
How do I
- Draw at the colours of my theme? Build a palette with
loom.NewPalette(loom.TrueColor, roles), whererolesmaps role names to colours. - Pick the chart glyphs? Set
Options.Chartstoplot.Braille,plot.Blocksorplot.ASCII. - Keep a pie round? Set
Options.CellAspectto the height of a cell over its width on your terminal. - Show
ago()values that change with time? WhenNeedsClock()is true, callTick()about once a minute. Only those boxes are evaluated again. - Draw the frame tuios puts around a popup? Call
loom.Framewith a title and an owner label, and draw the surface inside it. - Change the document and keep the state? Call
Replace(doc, true). - Draw again after the theme changed? Call
SetPalette.
API overview
| Name | Does |
|---|---|
New, Options | Makes a surface for a checked document. |
Surface.Render, Buffer | Draws the surface at a size into cells. |
Surface.Patch, Surface.Set | Changes the state. |
Surface.Damage | The rectangles repainted since the last call. |
Surface.Key, Surface.Mouse, Result, Effect | Input, and what it sends back. |
Palette, DefaultPalette, NewPalette, Depth | Colours by role at a colour depth. |
Frame | The frame a host puts around a floating surface. |
Limits
- loom draws any tree, valid or not, at any size up to 4096 by 4096 cells, without a panic. Layout measures each box once per width, so deep nesting stays cheap.
- Every number that sizes something, such as
bins, is clamped to its range. NaN and infinities take the default. - It drops control characters at the cell.
- The store comes from
tml.StoreFor, so a patch cannot groweach,listor the rows past the document limits. - One frame has a budget of 1,000,000 expression steps. Each box gets an equal share: 1,000,000 divided by the most boxes the document can build, and at least 100 steps. The share depends only on the document, so a box shows the same values in a full render and when it is built again alone.
Where it fits
- tml gives loom the tree, the state store, the bindings and the actions.
- plot draws the chart components.
- tuios uses loom for
tuios tml showpopups and panes. The daemon keeps each surface, and every attached client draws it. - The pictures on these pages go from loom's cells to PNG through shot.
The package imports tml, plot, ultraviolet and charmbracelet/x/ansi. It imports no tuios package.
Versions
The module is at v0. The API can change between minor versions. Its tags have the folder name as a prefix, such as loom/v0.1.0. The source is in the loom folder of the tuios repository, under the MIT licence.
tml
The TML language as a Go library. Parse, print and validate documents for terminal surfaces, evaluate their bindings, run local actions and apply JSON Patch to their state.
plot
Bar, line, area, sparkline, gauge, histogram, heatmap, pie, mirrored and inline bar charts and a world map as terminal cells, in braille, block elements or ASCII, with theme roles in place of colours.
tuios lives only at tuios.dev and github.com/Gaurav-Gosain/tuios. tuios has no X or Twitter account. An account that offers a tuios token or presale is not this project.


























