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.

A test dashboard drawn by loom in a popup frame: pass and fail counts, a pass-rate gauge, columns of seconds per run, a failures table with a cursor row and two buttons
A TML document drawn by loom, in the frame a host puts around a surface.

The API reference is on pkg.go.dev.

Quickstart

go get tuios.dev/loom tuios.dev/tml
main.go
package 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 output of the program in a terminal: 412 passed, 3 failed, a gauge at 99.3 percent, and columns of seconds per run with an axis

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@latest

Each 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 AUR
tml 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 q or esc to quit when the document does not use the key, or ctrl+c at any time.
  • A close action quits, and tml prints its value as JSON. A copy action copies with OSC 52. emit, open, pane and links need a host such as tuios, so they do nothing here.
  • When the output is not a terminal, or with --print, tml draws the document once and writes it as text.
  • tml -h lists 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.

  • w and h take cells, a percentage, fill or fill:N. The fill boxes share the space that is left, by their weight N.
  • min-w, max-w, min-h and max-h bound a size. A fill box at its maximum gives the rest to the others.
  • pad, gap, grow, align and justify work 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.
Two rows of stat tiles. In the first, a fixed tile of 14 cells, a tile with one share and a tile with two shares. In the second, a quarter, a tile capped at 18 cells and a tile that takes the rest
Fixed, fill, fill:2, a percentage and a capped fill. The source is on the tml page.

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>
Four buttons and a hint on one line at 80 cells
At 80 cells
The same buttons on two lines at 40 cells, and the hint at the right on a third line
At 40 cells

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>
At 130 cells, the wide band: three stat tiles across the width
At 90 cells, the medium band: three stats on one line
At 50 cells, the narrow band: two stats on one line

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 use NewPalette with 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.

The test run at truecolor, with grounds and soft colours
TrueColor
The test run at 256 colours, close to the truecolor one
Color256
The test run at 16 colours: no grounds, and the cursor row and the primary button in reverse video
Color16
The test run in ASCII: hash bars, ASCII sparklines, a greater-than sign for the cursor and brackets around the buttons
ASCII

Updates: the retained tree

A surface keeps its tree of boxes between frames. Nothing is laid out or drawn again unless something changed.

  1. A state patch marks only the boxes whose bindings read the changed paths.
  2. The next Render evaluates those boxes again, lays the tree out, and repaints only the boxes whose content or place changed.
  3. Damage returns the rectangles repainted since its last call, including the renders that input caused. A host sends only those cells to the terminal.
  4. A Render with 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.

The dashboard after the patch. The cells of 413 passed, 8 skipped and the gauge are tinted. 3 failed, the chart and the failures table are not

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 key works from anywhere on the surface.
  • tab and shift+tab move the focus.
  • The focused table or list takes the arrow keys, enter, and s to 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.
The failures table after the keys down, down and s: sorted by time from the shortest, with the cursor still on TestDockClick
The table on the tml page after down, down and s. It has one sortable column, so s flips the order. The cursor keeps its row.
The tabs after a click on the Log tab: the Log tab is open and shows its code line
The tabs after a left click on Log.
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.

main.go
// 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)
	}
}
dashboard.tml
<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>
The dashboard the program shows: stats, a gauge, columns of seconds per run, a failures table and two buttons

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), where roles maps role names to colours.
  • Pick the chart glyphs? Set Options.Charts to plot.Braille, plot.Blocks or plot.ASCII.
  • Keep a pie round? Set Options.CellAspect to the height of a cell over its width on your terminal.
  • Show ago() values that change with time? When NeedsClock() is true, call Tick() about once a minute. Only those boxes are evaluated again.
  • Draw the frame tuios puts around a popup? Call loom.Frame with 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

NameDoes
New, OptionsMakes a surface for a checked document.
Surface.Render, BufferDraws the surface at a size into cells.
Surface.Patch, Surface.SetChanges the state.
Surface.DamageThe rectangles repainted since the last call.
Surface.Key, Surface.Mouse, Result, EffectInput, and what it sends back.
Palette, DefaultPalette, NewPalette, DepthColours by role at a colour depth.
FrameThe 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 grow each, list or 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 show popups 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.

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.

On this page