lattice

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

lattice

ci Go Reference

A layout engine for charm.land v2 terminal UIs.

Declare the layout once — anchored to the screen edges, to each other, sized in proportions — and think only about panel contents. Panels hand their computed size to the components inside them. A panel is always exactly its slot and never loses its border.

tree := lattice.Dock("root", lattice.Docked{
    Top:    []lattice.Cell{lattice.At(lattice.Len(1), topBar)},
    Bottom: []lattice.Cell{lattice.At(lattice.Len(1), footer)},
    Left:   []lattice.Cell{lattice.At(lattice.Len(28), sidebar)},
    Centre: lattice.Col("main",
        lattice.At(lattice.Fill(60), commits),
        lattice.At(lattice.Fill(40), diff),
    ),
}).MinScreen(60, 16)

No int(float64(w) * 0.35). No if leftW < 10 { leftW = 10 }. No rightW := w - leftW that stops being true at small sizes.

Install

go get github.com/kondr1/lattice

Requires Go 1.25 and the charm.land v2 line: bubbletea/v2, bubbles/v2, lipgloss/v2.

The shape of it

type model struct {
    layout   *teax.Layout
    branches list.Model
}

func (m *model) tree() lattice.Node {
    return lattice.Col("root",
        lattice.At(lattice.Len(1), lattice.Leaf("topbar").
            PaintString(func(w, h int) string { return bar.Width(w).Render(" title") })),
        lattice.At(lattice.Fill(1), lattice.Row("body",
            lattice.At(lattice.Len(28), lattice.Leaf("sidebar").
                Chrome(lattice.Chrome{Border: lattice.Rounded(),
                    Title: lattice.Title{Text: "Branches"}}).
                Bind(sizers.List(&m.branches)).
                PaintString(func(w, h int) string { return m.branches.View() })),
            lattice.At(lattice.Fill(1), lattice.Leaf("main")),
        )),
    )
}

func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
    switch msg := msg.(type) {
    case tea.WindowSizeMsg:
        m.layout.Resize(msg)
    case tea.MouseClickMsg:
        hit, _ := m.layout.Route(msg)
        if hit.InContent() && hit.Has("sidebar") {
            m.branches.Select(hit.Row())   // the row *is* the item index
        }
    }
    // One solve, at the end of every Update — a tree change is just another update.
    _ = m.layout.Update(m.tree())
    return m, nil
}

func (m *model) View() tea.View { return m.layout.View(m.tree()) }

go run ./examples/dashboard for the whole thing: focus, a hideable panel, a modal dialog, a context menu, and a minimum-screen notice. The other three programs in examples/ reproduce the bugs that shaped it.

What it guarantees

Every one of these is asserted by latticetest over every terminal size from 1×1 to 200×60, on every commit.

  • Every rectangle is inside its parent's content rectangle.
  • No cell has two owners, at any size — siblings overlap only where a container declared its children share a border, and only over that one run of cells.
  • A framed panel has all four border runs on screen, or is not drawn at all. There is no such thing as a three-sided box.
  • A painter cannot write outside its node. Not "should not" — the cells are clipped on the way out.
  • Absolute coordinates everywhere. Nothing probes the screen cell by cell to find out where a panel actually is.
  • Solving has no side effects, and rendering cannot resize a component.

When a layout does not fit, it degrades in a declared order and says so: the lowest-priority panels drop out, what is left is reported as Undersized, and below MinScreen a "80×24 needed — 62×18" notice appears instead of wreckage.

Why this exists

Because this arithmetic is easy to get wrong while looking straight at it. Not by other people — three of the bugs in the list below were found in lattice's own first draft, after it already had a passing test suite:

  • a coloured border that decoded to nothing and simply did not draw,
  • a context menu that stopped pointing at the click, but only in the corner,
  • a frame that cost 2 ms and 2.3 MB to paint.

Each has a standalone reproduction, importing no lattice code at all, in examples/README.md — worth reading before deciding to compute panel rectangles by hand, with this library or without it.

The rest of the list is the same thing found earlier, in the layers underneath.

Why not …

Instead of Because
writing a constraint solver ultraviolet/layout is a Cassowary solver already in the build. lattice wraps it, and works around its three sharp edges: Padding relocating children to the origin, Split returning slices owned by a process-global cache, and Split panicking rather than returning its error.
Style.Width(n) to size a panel It wraps — hard-breaking words — and never clips. One over-long row becomes two, the body outgrows the panel, and the panel clips its own bottom border away.
Style.Height(n) to bound a panel It only pads. align.go:61 returns the string unchanged when the content is taller than n.
MaxWidth/MaxHeight as a safety net They clip after the border is applied, so they cut through the frame.
lipgloss.Compositor for output Draw does not clip to the area it is given, and Render allocates Bounds()-sized output without translating by bounds.Min, so it is only correct at the origin. lattice composes on a lipgloss.Canvas, the one construct that hard-clips and is guaranteed to produce exactly w×h.
Layer.GetX/GetY for positions They are parent-relative, so absolute positions have to be recovered by probing Compositor.Hit cell by cell. Geometry only ever exposes absolute coordinates.
Percent(55)/Percent(45) beside a Len(24) The solver measures Percent against the whole area, not the leftover, so that does not mean what it looks like. Use Fill(55)/Fill(45), which take a weighted share of what is left. lattice warns when a container mixes the two.
resizing components in View() View has a value receiver, so the resize is discarded — it "works" only because View gets a fresh copy each frame. Bind applies sizes in Update; a sizer called while painting reports SizedDuringPaint instead.
a separate concept for screen edges A top bar is At(Len(1), …) first and a footer is At(Len(1), …) last. There is no m.height - FooterHeight left to get wrong.

Putting one layout over another

Three spellings, differing in one thing: whether the overlay takes part in the same solve.

A Stack — one solve, one geometry. Layers share the parent's content rectangle and are drawn in z order. A layer paints only the cells it writes, so what is underneath shows through without a compositor.

tree := lattice.Stack("root", baseLayout, overlay.Z(1))

This is the spelling for an overlay that is part of the same screen: a dimming layer, a banner, a watermark. One hit.ID() answers for both trees.

A full-screen Float — still one solve, but the overlay gains anchoring, a margin and Modal.

tree := baseLayout.Float(lattice.Float{
    ID:     "sheet",
    Node:   overlay,
    Anchor: lattice.AnchorCentre(),
    Size:   lattice.FloatSize{W: lattice.Share(100), H: lattice.Share(100)},
    Margin: lattice.Pad(1, 2),
    Modal:  true,
})

This is the spelling for a sheet or a dialog that covers everything: Margin leaves a frame of the layout below visible, and Modal makes hit.Blocked() true everywhere outside it.

Two solves, composed onto one screen — for an overlay that is genuinely a separate thing, with its own IDs, its own area and its own update cycle.

gb, _ := lattice.Solve(base,  lattice.R(0, 0, w, h))
gp, _ := lattice.Solve(panel, lattice.R(4, 1, 8, 3))   // absolute coordinates

canvas := lipgloss.NewCanvas(w, h)
lattice.Draw(gb, base, canvas)
lattice.Draw(gp, panel, canvas)   // composes over the first
out := canvas.Render()

Draw writes at absolute coordinates onto a caller-owned screen, and never touches a cell outside its own area — so the second layout can only paint its own rectangle. Hit testing becomes a fall-through:

if h := gp.Hit(x, y); !h.Empty() {
    …          // the overlay
} else {
    h = gb.Hit(x, y)
}

The trade-off is that teax.Layout holds one geometry, so this last spelling does not go through it: solving, drawing and routing the two layouts is the caller's job. The first two do go through it, and are what an application wants nearly always.

Collapsed borders

A frame is the most expensive decoration a terminal layout has — two rows and two columns per panel — and where two panels meet, the terminal spends two of them on what reads as one edge:

┃ README.md            M ┃│diff --git a/README.md
┗━━━━━━━━━━━━━━━━━━━━━━━━┛│index ce01362..3b18e51
╭─ Staged (0) ───────────╮│--- a/README.md

CollapseBorders on the container shares it. Four panels in two columns give back two columns and two rows — one more file in the list, one more line of diff — and, more to the point, look drawn rather than stacked:

lattice.Row("body",
    lattice.At(lattice.Fill(35), lattice.Col("files",
        lattice.At(lattice.Fill(50), panel("working", "Working")),
        lattice.At(lattice.Fill(50), panel("staged", "Staged")),
    ).CollapseBorders()),
    lattice.At(lattice.Fill(65), lattice.Col("detail",
        lattice.At(lattice.Fill(70), panel("diff", "Diff")),
        lattice.At(lattice.Fill(30), panel("commit", "Commit")),
    ).CollapseBorders()),
).CollapseBorders()
╭─Working───────────┬─Diff─────────────────────────────────╮
│                   │                                      │
│                   │                                      │
├─Staged────────────┤                                      │
│                   │                                      │
│                   ├─Commit───────────────────────────────┤
│                   │                                      │
╰───────────────────┴──────────────────────────────────────╯

Three things make this the library's job rather than the caller's, and all three need facts only the solver has:

Which pairs are adjacent, after everything else has happened. Doing it by hand means dropping one side of one panel with Border.Sides, per pair, and redoing it whenever the arrangement changes. Hidden(true) on the diff panel silently makes its neighbour's dropped side wrong. Collapsing is recomputed each solve from the children that survived hiding and degradation.

The junctions. Where four panels meet, the shared cell has to be a ┼; at a T-junction, ┬/┴/├/┤. A dropped side leaves whatever the surviving panel's corner rune was — a ╮ where a ┬ belongs. After the tree is painted, every cell where runs meet is redrawn from the border set's own Middle* runes, so a collapsed Thick border meets in heavy tees and a Rounded one in light ones.

Precedence. A shared run is drawn once, by whichever of the two panels draws last: the higher Z first, then declaration order. So a highlighted panel wants raising while it is highlighted, or the runs it shares stay in its neighbours' style and it keeps one grey edge on an otherwise accented frame:

panel := lattice.Leaf("commits").Chrome(chrome)
if focused {
    panel = panel.Z(1)      // its border wins every run it shares
}

Raising it wins the run without taking it out of the picture — it still meets its neighbours in tees rather than closing itself off in corners.

The overlap is the one place the no-overlap invariant is relaxed, and it is relaxed visibly:

v, _ := g.View("body")
v.Shared()          // the one-cell runs its children share
v.Owns(x, y)        // whether this node is the one painting that cell
g.Hit(x, y)         // routes a click on the shared border to that same node

Per-pair opt-outs: Detached() on a child keeps its edges to itself, a Gap means there is nothing to share, and a pair whose two sides do not both bring a border to the edge keeps the ordinary boundary. At sizes where a panel would be left thinner than its own frame, the container falls back to an ordinary split — the layout merely looks as it did before.

Resizing

The split between two panels is a constant in the tree — Fill(35), Fill(65) — and a user who wants a wider diff cannot have one. Split makes the proportion a value the application owns:

split := lattice.NewSplit(35, 65)

lattice.Row("body",
    lattice.At(split.At(0), files),
    lattice.At(split.At(1), detail),
).Resizable(split)

The solver records which cells each divider occupies, so a hit knows:

if hit := g.Hit(x, y); hit.OnDivider() {
    d, _ := hit.Divider()
    d.MoveTo(x)            // clamped by both neighbours' MinSize
}

With Bubble Tea the gesture is one call at the top of the mouse handler — press, motion and release are teax's business, because lattice takes coordinates rather than events:

case tea.MouseMsg:
    if m.layout.Drag(msg, &m.resize) {
        return m, nil      // the drag consumed it
    }

Three things the library owns because a caller cannot:

Which cells are a divider. With collapsed borders it is the shared run; across a gap it is the gap; with neither it is the two frames that meet, because a line between two panels is a two-cell target and a nothing-wide one is not a target at all. Either way the solver knows and the caller would have to reconstruct it — including which pairs survived hiding and degradation.

The clamp. A divider redistributes between its own two neighbours and nothing else; their total is preserved, and neither may be squeezed below its MinSize. Getting that wrong is how a pane vanishes and cannot be brought back. Divider.Range() is the clamp made visible.

Persistence. What moves is a proportion, not a cell count, so a layout the user resized and the terminal then resized keeps its proportion. And a Split marshals to [35,65], which is what goes in the configuration file beside the theme:

raw, _ := json.Marshal(split)      // [7,13]
_ = json.Unmarshal(raw, split)     // the same layout, next start

Packages

Package Contents
lattice Node, Cell, constraints, Chrome, Solve, Geometry, View, Hit, Surface, Render, Float/Anchor/Extent, Diagnostic
lattice/sizers Sizer adapters for every bubbles component
lattice/teax teax.Layout — the Update/View split, tea.View construction, mouse routing, divider drags
lattice/latticetest invariant assertions, a cell-level Screen, size sweeps, golden helpers

The core imports only ultraviolet and lipgloss/v2 — never bubbletea or bubbles — so a layout is testable without a TTY or a tea.Program.

Testing a layout

func TestLayout(t *testing.T) {
    latticetest.ForEachSize(t, 1, 1, 200, 60, func(t *testing.T, w, h int) {
        g := latticetest.Solve(t, tree(), w, h)
        latticetest.AssertAll(t, g)
        latticetest.AssertFramesIntact(t, latticetest.Render(t, g, tree()), g)
    })
}

AssertAll is the geometry invariants — in bounds, one owner per cell, children inside their parents. On a rendered screen there are AssertFramesIntact, AssertClippedTo, AssertFullCoverage and, for collapsed borders, AssertJunctions: every cell of every shared run joins a neighbouring run in a direction if and only if that neighbour joins back.

That sweep varies the terminal for one declared layout. latticetest.FuzzTree varies the layout as well — random nesting, gaps, chrome, hidden nodes, priorities and floats — for the combinations nobody sits down and enumerates:

func FuzzLayout(f *testing.F) { latticetest.FuzzTree(f) }

Geometry.Dump() is the golden artifact — stable, ANSI-free, and a diff points straight at the rectangle that moved. latticetest.GoldenGeometry and -update handle the files.

Performance

A twelve-node dashboard at 120×40, on a Ryzen 9 7950X3D:

Solve (cache warm) ~31 µs, 15 KB
Solve (resizing, cache cold every frame) ~62 µs, 23 KB
Draw (painting a frame) ~132 µs, 19 KB
Render (painting + ANSI encoding) ~440 µs, 53 KB
Hit ~9 ns, no allocation

Solving on every Update costs less than a keystroke's worth of anything else.

Non-goals

No widgets, no focus management, no scrolling or virtualisation, no text-wrapping engine (that is lipgloss and x/ansi), no animation, no theming. lattice decides where things are and that they stay there; bubbles decides what they are.

Three of these come up as feature requests often enough to be worth answering properly, because in each case the thing people want is real — it is the spelling that would be wrong.

"Let panels overlap — give me a negative gap"

The solver underneath supports it; lattice rejects it, because Row and Col promise to tile and an overlap makes three things ambiguous at once: which sibling owns a shared cell, which one a click belongs to, and which one's border survives being drawn over.

Overlap is available where it is declared as overlap: Stack and Float may intersect anything, and the assertions exempt them for exactly that reason.

What a negative gap is nearly always reaching for is collapsed borders — neighbours sharing one line instead of drawing two — and that has its own spelling on the container:

lattice.Row("body",
    lattice.At(lattice.Fill(35), files),
    lattice.At(lattice.Fill(65), detail),
).CollapseBorders()

The children do overlap, by exactly the one run of cells their frames have in common — but the ambiguity is gone, because the library answers all three questions instead of leaving them open. View.Shared() says where the run is, View.Owns(x, y) says whose cell it is, Geometry.Hit routes the click to that same panel, and the higher Z wins the border with declaration order breaking the tie. Where runs meet, the cell is redrawn as the tee or cross its neighbours imply.

See Collapsed borders below.

"Make the panel as tall as its wrapped text"

Wrapping and layout are circular: height depends on the wrapped text, which depends on width, which depends on the layout, which depends on the heights. lattice breaks the circle in one direction — the layout decides the size, the painter fills what it was given, and the overflow is clipped. That is deliberate: wrapping is what turns one long row into two, which makes the body taller than its panel, which is how a panel loses its own bottom border.

So wrapping is opt-in per node, and delegated:

lattice.Leaf("detail").Wrap(true)     // ansi.Wrap, inside the content rect

If the content is genuinely longer than the panel, that is a scrolling problem, not a layout one — put a viewport in the panel and bind it:

lattice.Leaf("detail").
    Bind(sizers.Viewport(&m.detail)).
    PaintString(func(w, h int) string { return m.detail.View() })

Content-driven sizing does exist where it is not circular: Fit measures a float's height from its already-resolved width.

"Let a node declare its own size — 50% wide"

A node already has a size: the one its cell was given by its parent. Letting it declare a second one creates two sources of truth for one rectangle, and the space it gives up belongs to nobody — the parent's split has already committed it, so the result is a hole rather than a larger sibling.

The constraint belongs on the parent's side, where the leftover has somewhere to go:

lattice.At(lattice.Percent(50), node)   // not node.Percent(50)

MaxSize is the one exception, and it says so: it caps the rectangle, stops tiling its parent, and leaves the surplus unpainted. Reach for it only when the cap is about the node's contents and the slot is flexible.

Licence

MIT. See LICENSE.

Documentation

Overview

Package lattice is a layout engine for charm.land v2 terminal UIs.

Declare the layout once — anchored to the screen edges, to each other, sized in proportions — and think only about panel contents. Panels hand their computed size to the components inside them. A panel is always exactly its slot and never loses its border.

The shape of it

A layout is a tree of Node values. Row and Col split their content rectangle along one axis, Stack gives every child the whole of it, and Leaf is where content goes. Each child of a row or column is a Cell: a Constraint paired with a node.

tree := lattice.Col("root",
	lattice.At(lattice.Len(1), lattice.Leaf("topbar")),
	lattice.At(lattice.Fill(1), lattice.Row("body",
		lattice.At(lattice.Len(24), lattice.Leaf("sidebar")),
		lattice.At(lattice.Fill(1), lattice.Leaf("main")),
	)),
	lattice.At(lattice.Len(1), lattice.Leaf("footer")),
)

Solve turns that into a Geometry: every node's absolute rectangle, plus whatever the solve has to complain about.

g, err := lattice.Solve(tree, lattice.R(0, 0, 100, 30))

A Node is an immutable value. Modifiers return copies, so a tree can be built fresh every frame from the current model without aliasing anything.

Constraints

Fill is the one to reach for. It takes a weighted share of what is left after the fixed-size siblings are satisfied, so Fill(55) and Fill(45) split the remainder 55/45 however many Len siblings there are. That is what replaces hand-written int(float64(w) * 0.55) factors.

Percent and Ratio are measured against the container's *whole* extent, not the leftover, so they do not compose with Len siblings. Mixing the two kinds in one container is reported as CodeMixedConstraints rather than left to be discovered on screen.

Min and Max bound a cell. Note that the underlying solver silently relaxes Min when space runs out; lattice detects that itself and reports it.

Chrome

Chrome is a node's frame: border, the titles spliced into that border, the padding inside it, the background behind it. It is the one place in the library that knows border arithmetic — content rectangles, minimum sizes and hit rows are all derived from it, so the three competing dialects of "subtract two" that hand-written layouts accumulate cannot come back.

panel := lattice.Leaf("sidebar").Chrome(lattice.Chrome{
	Border: lattice.Rounded(),
	Title:  lattice.Title{Text: "Branches"},
})

A title costs no row: it is written into the border run, so a titled panel is exactly as tall as an untitled one. A node whose rectangle cannot hold its frame is not drawn at all — a panel is whole or absent, never a three-sided box.

Collapsed borders

A frame is the most expensive decoration a terminal layout has, and where two panels meet the terminal spends two rows or two columns on what reads as one edge. Node.CollapseBorders makes a container's adjacent children share it:

lattice.Row("body",
    lattice.At(lattice.Fill(35), files),
    lattice.At(lattice.Fill(65), detail),
).CollapseBorders()

The children overlap by exactly one cell — the only place the no-overlap invariant is relaxed, and it is relaxed visibly. The container records the run (View.Shared), one panel owns every cell of it (View.Owns), and a click on it lands on that same panel. Where runs meet, the cell is redrawn as the tee or cross its neighbours imply, from the border set's own MiddleLeft/Middle/MiddleTop runes, so a grid looks drawn rather than overlapped.

Which pairs share is worked out per solve, from the children that survived hiding and degradation, which is what the hand-written version — dropping one side of one panel with Border.Sides — cannot do: hide a panel and its neighbour is left with a dropped side and nothing to share it with. A pair shares only when both sides bring a border to the edge; Node.Detached opts a child out, and a Node.Gap means there is nothing to share in the first place.

A shared run is drawn once, by whichever panel draws last: the higher Node.Z first, then the later declaration. A highlighted panel therefore wants raising while it is highlighted — Z(1) on the focused one — or the runs it shares stay in its neighbours' style and it keeps one grey edge on an otherwise highlighted frame. Raising it wins the run without taking it out of the picture: it still meets its neighbours in tees.

Resizing

The line between two panels is a constant in the tree — Fill(35), Fill(65) — until the application takes it over. NewSplit makes the proportion a value it owns, and Node.Resizable makes the container's internal edges draggable:

split := lattice.NewSplit(35, 65)

lattice.Row("body",
    lattice.At(split.At(0), files),
    lattice.At(split.At(1), detail),
).Resizable(split)

The solver records which cells each divider occupies — the shared run where the neighbours collapse their borders, the gap where the container has one, the two frames that meet where it has neither — so a hit reports Hit.OnDivider and hands back a Divider. Moving one changes the Split, and the next solve does the rest:

if hit := g.Hit(x, y); hit.OnDivider() {
    d, _ := hit.Divider()
    d.MoveTo(x)          // clamped by both neighbours' MinSize
}

The clamp is the library's, because getting it wrong is how a pane vanishes and cannot be brought back: a divider redistributes between its own two neighbours, their total is preserved, and neither may go below its minimum. What moves is a proportion, so a layout resized by the user and then resized by the terminal keeps its proportion rather than its cell count — and a Split marshals to JSON, so pane sizes belong in a configuration file beside the theme.

The drag gesture is not here. lattice takes coordinates, not mouse events; press, motion and release live in github.com/kondr1/lattice/teax, where the rest of the event routing already is.

Rendering

Render takes the stored geometry and a freshly declared tree, matched by ID: geometry from the update path, painters from the current model value. Painters receive a Surface whose every write is clipped to the node's content rectangle, so overflow costs content and never the frame.

out := lattice.Render(g, tree)

That split is deliberate. Bubble Tea's View has a value receiver, so a pointer captured when the tree was first declared may be stale: painters must be rebuilt every frame, and geometry must not be recomputed. A tree whose Geometry.Shape differs from the geometry's is a programmer error, and it is reported loudly.

Sizing components

bubbles components size themselves imperatively, on pointer receivers. Node.Bind attaches a Sizer; Geometry.Apply hands every bound node its content size. Apply runs in Update, where the model value survives — a resize attempted from inside a painter is refused and reported as CodeSizedDuringPaint.

See package github.com/kondr1/lattice/sizers for the adapters, and github.com/kondr1/lattice/teax for the Bubble Tea glue that calls Solve and Apply at the end of every Update.

Hit testing

Geometry.Hit answers in one step what mouse routing used to reconstruct by hand: which node, where inside it, which row of its content, whether the point landed on the border, and whether a modal is swallowing it.

hit := g.Hit(msg.X, msg.Y)
if hit.InContent() && hit.Has("sidebar") {
	list.Select(hit.Row())
}

Every coordinate the API exposes is absolute. There is no parent-relative getter, so nothing has to probe the screen cell by cell to recover where a panel actually is.

Floats

A dialog, a context menu or a corner spinner is a Float: a node placed over the layout rather than in it, positioned by an Anchor and sized by an Extent. Floats are clamped to their container by default — flipped to the other side of their anchor first, then shifted, then trimmed — which is why a menu opened at the edge of the screen cannot run off it.

Degradation

When a container cannot fit its children's minimum sizes, the lowest-priority droppable child is removed, and then the next, until the rest fit. Each drop is reported. What survives under its minimum is reported too. Below the root's Node.MinScreen the renderer draws a "80×24 needed — 62×18" notice instead of a mangled layout.

Solve returns an error only for programmer mistakes — a duplicate ID, an empty container, a negative gap — because no screen size can fix those. Everything size-related is a Diagnostic, so a cramped terminal degrades instead of crashing, and tests can assert that there are none.

Testing

Package github.com/kondr1/lattice/latticetest turns the invariants into assertions and runs them over every terminal size in a range. That sweep is the acceptance gate: an invariant that holds from 1×1 to 200×60 is a guarantee rather than a happy path.

Putting one layout over another

Stack layers two trees in one solve, sharing a geometry and a hit test; a Float sized to Share(100) does the same with an anchor, a margin and Modal. For an overlay that is genuinely separate — its own IDs, its own area, its own update cycle — solve it separately and compose with Draw, which writes at absolute coordinates onto a caller-owned screen and never touches a cell outside its own area.

Non-goals

No widgets, no focus management, no scrolling or virtualisation, no text-wrapping engine, no animation, no theming. lattice decides where things are and that they stay there; bubbles decides what they are.

Three of these are asked for often enough to be worth answering here, because what is wanted is real and only the spelling would be wrong.

Overlapping siblings — a negative gap — are rejected because Row and Col promise to tile, and an overlap makes it ambiguous which sibling owns a cell, which one a click belongs to, and whose border survives. Overlap is available where it is declared as such, in Stack and Float. What a negative gap usually wants is collapsed borders, and that has its own spelling: Node.CollapseBorders on the container, which shares the edge between adjacent children and answers all three questions — View.Owns says whose cell it is, Geometry.Hit routes the click to that same panel, and the higher Node.Z wins the border, with declaration order breaking the tie.

Sizing a panel to its wrapped text is circular — height depends on the wrap, which depends on width, which depends on the layout. lattice breaks the circle by deciding size first and clipping the overflow, because wrapping is precisely what makes a body taller than its panel and costs the panel its border. Wrapping is therefore opt-in per node (Node.Wrap) and delegated to x/ansi; content longer than its panel is a scrolling problem, so put a viewport in it. Where the circle does not close, content-driven sizing exists: Fit measures a float's height from its resolved width.

A node cannot declare its own size because it already has one — the size its cell was given. A second source of truth for one rectangle leaves the space it gives up belonging to nobody, since the parent's split has already committed it. Put the constraint on the cell, where the surplus has somewhere to go. Node.MaxSize is the one exception and documents its own cost.

Example

A layout is a tree of nodes; solving it gives every node an absolute rectangle. Fill takes a share of what is left after the fixed sizes are satisfied, so the body gets whatever the bars do not.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	tree := lattice.Col("root",
		lattice.At(lattice.Len(1), lattice.Leaf("topbar")),
		lattice.At(lattice.Fill(1), lattice.Row("body",
			lattice.At(lattice.Len(24), lattice.Leaf("sidebar")),
			lattice.At(lattice.Fill(1), lattice.Leaf("main")),
		)),
		lattice.At(lattice.Len(1), lattice.Leaf("footer")),
	)

	g, err := lattice.Solve(tree, lattice.R(0, 0, 80, 24))
	if err != nil {
		panic(err)
	}

	w, h, _ := g.Size("main")
	fmt.Printf("main is %dx%d\n", w, h)
	fmt.Print(g.Dump())
}
Output:
main is 56x22
area 0,0 80x24
col root 0,0 80x24 min=24x2
  leaf topbar [Len(1)] 0,0 80x1
  row body [Fill(1)] 0,1 80x22
    leaf sidebar [Len(24)] 0,1 24x22
    leaf main [Fill(1)] 24,1 56x22
  leaf footer [Len(1)] 0,23 80x1

Index

Examples

Constants

View Source
const DefaultTitleInset = 2

DefaultTitleInset is how far from the corner a title starts when the Title does not say otherwise.

Variables

This section is empty.

Functions

func DefaultTooSmall

func DefaultTooSmall(area Rect, want Size) string

DefaultTooSmall is the notice drawn when the terminal is smaller than the layout's declared minimum.

func Render

func Render(g *Geometry, tree Node, opts ...RenderOption) string

Render draws a solved layout and returns the frame.

It takes both the stored geometry and a freshly declared tree, matched by ID: geometry comes from the update path, painters from the current model value. That split is the honest answer to Bubble Tea's value semantics — View has a value receiver, so any pointer captured when the tree was first declared may be stale, which means painters must be rebuilt every frame while geometry must not be recomputed.

The frame is composed on a lipgloss.Canvas, the only construct in lipgloss that hard-clips: its output is exactly the area's width and height, always.

Types

type Align

type Align int

Align positions a title along its border.

const (
	AlignLeft Align = iota
	AlignCentre
	AlignRight
)

type Anchor

type Anchor struct {
	// contains filtered or unexported fields
}

Anchor says where a float goes. Build one with AnchorCentre, AnchorCorner, AnchorEdge, AnchorPoint or AnchorTo.

func AnchorCentre

func AnchorCentre() Anchor

AnchorCentre centres the float in its container.

func AnchorCorner

func AnchorCorner(c Corner) Anchor

AnchorCorner pins the float to a corner of its container.

func AnchorEdge

func AnchorEdge(e Edge, align Align) Anchor

AnchorEdge pins the float to an edge, aligned along it.

func AnchorPoint

func AnchorPoint(p Position, g Gravity) Anchor

AnchorPoint puts a corner of the float on an absolute point — a context menu at the cell that was clicked.

func AnchorTo

func AnchorTo(id ID, side Side, align Align) Anchor

AnchorTo puts the float beside another node, aligned to it.

type Background

type Background struct {
	Rune  rune
	Style lipgloss.Style
}

Background is what fills a node's rectangle before anything is painted on it. A node without one is transparent: it paints only the cells it writes.

type Border

type Border struct {
	lipgloss.Border
	Top, Right, Bottom, Left bool
}

Border is a lipgloss border together with which of its sides are actually drawn. The embedded lipgloss.Border supplies the runes; the four bools decide which edges exist, and therefore how much room the frame costs.

func Double

func Double() Border

Double is a full border in double lines.

func NoBorder

func NoBorder() Border

NoBorder draws no frame at all.

func Normal

func Normal() Border

Normal is a full border with square corners.

func Rounded

func Rounded() Border

Rounded is a full border with rounded corners.

func Thick

func Thick() Border

Thick is a full border in heavy lines.

func (Border) Inset

func (b Border) Inset() Padding

Inset is how many cells the border costs on each side.

func (Border) Sides

func (b Border) Sides(top, right, bottom, left bool) Border

Sides returns a copy of the border with only the named sides drawn.

type Cell

type Cell struct {
	Size Constraint
	Node Node
}

Cell is a child of a Row or Col together with the constraint that sizes it along the container's axis.

func At

func At(size Constraint, n Node) Cell

At pairs a constraint with a node, for use in Row and Col.

type Chrome

type Chrome struct {
	Border  Border
	Title   Title // spliced into the top border
	Footer  Title // spliced into the bottom border
	Padding Padding
	Fill    *Background    // background; nil means transparent
	Style   lipgloss.Style // border colours
}

Chrome is a node's frame: its border, the titles spliced into that border, the padding inside it and the background behind it.

It is the one place in the library that knows border arithmetic. Everything downstream — the content rectangle, the minimum size, where a title goes, which row a mouse click landed on — is derived from here, so the three competing dialects of "subtract two" that hand-written layouts accumulate cannot come back.

Example

Chrome owns the border arithmetic. The content rectangle, the minimum size and the row a click landed on all come from it, so nothing else has to know how wide a border is.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	c := lattice.Chrome{
		Border:  lattice.Rounded(),
		Title:   lattice.Title{Text: "Branches"},
		Padding: lattice.Pad(0, 1),
	}

	r := lattice.R(10, 5, 30, 8)
	fmt.Println("rect   ", r)
	fmt.Println("content", c.Content(r))
	fmt.Println("needs   ", c.MinSize(20, 4), "to hold 20x4 of content")
	fmt.Println("fits 1x1?", c.Fits(lattice.R(0, 0, 1, 1)))
}
Output:
rect    (10,5)-(40,13)
content (12,6)-(38,12)
needs    24x6 to hold 20x4 of content
fits 1x1? false

func (Chrome) Content

func (c Chrome) Content(r Rect) Rect

Content is the rectangle inside the chrome. It is never larger than r and never negative: when there is not enough room it collapses in place rather than relocating.

func (Chrome) Draw

func (c Chrome) Draw(s *Surface, r Rect)

Draw paints the background and the frame into r, in the surface's coordinates.

The frame is written cell by cell rather than through lipgloss's Style.Border, and it is painted before the content is clipped into the inner rectangle. That ordering is the load-bearing decision of the whole renderer: overflow costs content, never the frame, so a panel cannot lose a border to a row that turned out one cell too wide.

func (Chrome) Empty

func (c Chrome) Empty() bool

Empty reports whether the chrome draws nothing at all.

func (Chrome) Fits

func (c Chrome) Fits(r Rect) bool

Fits reports whether r can hold the frame. It deliberately asks only about the border, not the padding: padding collapses quietly, but a frame that does not fit must not be drawn at all.

func (Chrome) Inset

func (c Chrome) Inset() Padding

Inset is the total gap between a node's rectangle and its content: the border plus the padding inside it.

func (Chrome) MinSize

func (c Chrome) MinSize(contentW, contentH int) Size

MinSize is the smallest rectangle that can hold this chrome around content of the given size.

func (Chrome) Titles

func (c Chrome) Titles(r Rect) []Rect

Titles returns the cells the spliced titles occupy in r: the title, the footer, or neither.

type Clamping

type Clamping int

Clamping says whether a float may leave its container.

const (
	// ClampToScreen flips the float to the other side of its anchor when it
	// would overflow, then shifts it, then trims it. This is the default, and
	// it is why a context menu opened near an edge cannot run off screen.
	ClampToScreen Clamping = iota
	// ClampNever places the float exactly where the anchor says and neither
	// flips nor shifts it. It is still trimmed to its container: a rectangle
	// outside the screen is not something the geometry will ever report.
	ClampNever
)

type Code

type Code int

Code identifies what went wrong. Codes are stable; messages are not, so assert on codes.

const (
	// CodeUndersized: the node got less room than its declared minimum.
	CodeUndersized Code = iota
	// CodeDropped: the node was removed so its siblings could fit.
	CodeDropped
	// CodeNoRoom: the node's rectangle cannot hold its own chrome, so it is
	// not drawn at all. A panel is whole or absent, never a three-sided box.
	CodeNoRoom
	// CodeMixedConstraints: a container mixes Percent/Ratio (measured against
	// the total) with Len/Min/Max (measured in cells). The result is rarely
	// what the author meant; Fill composes with cell sizes, Percent does not.
	CodeMixedConstraints
	// CodeUnusedSpace: a container left cells unassigned. Usually a missing
	// Fill(1).
	CodeUnusedSpace
	// CodeSolverPanic: the underlying constraint solver failed. The container
	// falls back to giving its children nothing.
	CodeSolverPanic
	// CodeShapeDrift: the tree handed to the renderer is not the tree that was
	// solved.
	CodeShapeDrift
	// CodeSizedDuringPaint: a sizer ran in the render path, where its effect
	// would be discarded.
	CodeSizedDuringPaint
	// CodeMissingPainter: geometry named a node the render tree has no painter
	// for.
	CodeMissingPainter
)

func (Code) String

func (c Code) String() string

type Collapse

type Collapse int

Collapse says what happens to a child when its container cannot fit every child's minimum size.

const (
	// CollapseDrop removes the child and gives its space to its siblings.
	CollapseDrop Collapse = iota
	// CollapseClip keeps the child at less than its minimum and clips it.
	CollapseClip
	// CollapseKeep never drops the child; siblings shrink first.
	CollapseKeep
)

func (Collapse) String

func (c Collapse) String() string

type Constraint

type Constraint = layout.Constraint

Constraint sizes one cell of a Row or Col along the container's axis. It is an alias for the ultraviolet solver's constraint type, so constraints built here can be handed to that solver directly.

When the solver cannot satisfy everything, it relaxes in this priority order, highest first: Min, Max, Len, Percent, Ratio, Fill.

func Fill

func Fill(weight int) Constraint

Fill takes a weighted share of whatever is left after the higher-priority constraints are satisfied. This is the replacement for hand-written int(float64(w)*0.55) factors: Fill(55) and Fill(45) split the leftover 55/45 however many fixed-size siblings there are.

Example

Fill composes with fixed-size siblings; Percent does not. Percent is measured against the container's whole extent, so 55 and 45 beside a Len(20) claim 120 cells of a 100-cell row. The solver relaxes the two lowest-priority claims equally, and a 55/45 split arrives as 40/40 — which is not a rounding error, it is a different layout. Fill asks for a share of the leftover, and gets it.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	area := lattice.R(0, 0, 100, 3)

	withFill := lattice.MustSolve(lattice.Row("row",
		lattice.At(lattice.Len(20), lattice.Leaf("fixed")),
		lattice.At(lattice.Fill(55), lattice.Leaf("a")),
		lattice.At(lattice.Fill(45), lattice.Leaf("b")),
	), area)

	withPercent := lattice.MustSolve(lattice.Row("row",
		lattice.At(lattice.Len(20), lattice.Leaf("fixed")),
		lattice.At(lattice.Percent(55), lattice.Leaf("a")),
		lattice.At(lattice.Percent(45), lattice.Leaf("b")),
	), area)

	for _, id := range []lattice.ID{"fixed", "a", "b"} {
		fw, _, _ := withFill.Size(id)
		pw, _, _ := withPercent.Size(id)
		fmt.Printf("%-5s  Fill %3d   Percent %3d\n", id, fw, pw)
	}
}
Output:
fixed  Fill  20   Percent  20
a      Fill  44   Percent  40
b      Fill  36   Percent  40

func Len

func Len(n int) Constraint

Len is exactly n cells. Negative values are treated as zero.

func Max

func Max(n int) Constraint

Max is a ceiling of n cells.

func Min

func Min(n int) Constraint

Min is a floor of n cells. Note that the solver silently relaxes Min when space runs out; lattice detects that itself and reports CodeUndersized.

func Percent

func Percent(p int) Constraint

Percent is a share of the container's *total* extent, clamped to 0..100.

Percent is evaluated against the whole area, not the leftover, so it does not compose with Len siblings: [Len(24), Percent(55), Percent(45)] does not leave the two percentages splitting what is left over. Use Fill for that.

func Ratio

func Ratio(num, den int) Constraint

Ratio is num/den of the container's *total* extent. Like Percent it is measured against the whole area. A non-positive denominator is treated as 1.

func Weights

func Weights(ws ...int) []Constraint

Weights turns a list of proportions into Fill constraints: Weights(35, 65) is []Constraint{Fill(35), Fill(65)}.

type Corner

type Corner int

Corner names one corner of a rectangle.

const (
	CornerTopLeft Corner = iota
	CornerTopRight
	CornerBottomLeft
	CornerBottomRight
)

type Diagnostic

type Diagnostic struct {
	ID        ID
	Severity  Severity
	Code      Code
	Message   string
	Want, Got Size
}

Diagnostic is something the layout did that the author probably did not intend. Diagnostics are data, not errors: a terminal too small to hold the declared layout degrades and reports, it does not fail.

Solve returns an error only for programmer mistakes — duplicate IDs, empty containers, negative gaps — which no screen size can fix.

func Draw

func Draw(g *Geometry, tree Node, scr uv.Screen, opts ...RenderOption) []Diagnostic

Draw paints a solved layout onto a screen the caller owns, in absolute coordinates, and returns whatever went wrong. Use it to compose a lattice layout into a larger ultraviolet surface; use Render for a frame.

func (Diagnostic) String

func (d Diagnostic) String() string

type Divider

type Divider struct {
	// contains filtered or unexported fields
}

Divider is a handle on one movable edge between two children.

It is opaque and it is a value: it names a container and an edge, and reads everything else — where the edge is now, how far it may travel — from the geometry it came from. Move it and the Split changes; the layout follows on the next solve, which is the same rule everything else in the library obeys.

func (Divider) Between

func (d Divider) Between() (before, after ID)

Between names the two children the divider sits between.

func (Divider) Horizontal

func (d Divider) Horizontal() bool

Horizontal reports whether the divider moves along x — true in a Row, false in a Col.

func (Divider) ID

func (d Divider) ID() ID

ID is the container whose children the divider sits between.

func (Divider) Index

func (d Divider) Index() int

Index is which of that container's edges this is, counting from the first. Together with Divider.ID it names the divider across solves, which is what a drag in progress needs: the geometry is rebuilt every frame, the edge is still the same edge.

func (Divider) MoveBy

func (d Divider) MoveBy(delta int) bool

MoveBy moves the divider by a number of cells, clamped as Divider.MoveTo.

func (Divider) MoveTo

func (d Divider) MoveTo(pos int) bool

MoveTo moves the divider's leading edge to an absolute coordinate, clamped by both neighbours' minimum sizes. It reports whether the split changed.

It changes the Split, not the geometry: the layout is what the next solve makes of the new proportion, exactly as it would be for any other change to the tree.

func (Divider) Range

func (d Divider) Range() (lo, hi int)

Range is the leading-edge positions the divider may be moved to, in absolute coordinates and inclusive. It is the clamp made visible: neither neighbour may be squeezed below its minimum size, so a pane cannot be dragged out of existence and left unrecoverable.

func (Divider) Rect

func (d Divider) Rect() Rect

Rect is the cells the divider occupies: the shared run where the neighbours collapse their borders, the gap where the container has one, and the two frames that meet where it has neither.

func (Divider) Valid

func (d Divider) Valid() bool

Valid reports whether the divider refers to an edge.

type Docked

type Docked struct {
	Top, Bottom, Left, Right []Cell
	Centre                   Node
}

Docked describes edge bars around a centre, for Dock.

type Edge

type Edge int

Edge names one edge of a rectangle.

const (
	EdgeTop Edge = iota
	EdgeRight
	EdgeBottom
	EdgeLeft
)

type Extent

type Extent struct {
	// contains filtered or unexported fields
}

Extent is one dimension of a floating node, expressed against the room available for it. It is the replacement for the five copies of

boxW := m.width - 4
if boxW > 70 { boxW = 70 }
if boxW < 20 { boxW = 20 }

that a dialog-heavy app accumulates, each with its own arithmetic and one of them with an extra -2 nobody can explain.

The zero Extent means "as small as the node says it needs to be".

Example

Extent is the algebra that replaces a dialog's hand-written width clamp: min(width-4, 60), floor 24, written once and read in order.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	width := lattice.Share(100).Minus(4).Clamp(24, 60)

	for _, available := range []int{20, 40, 100} {
		fmt.Printf("available %3d -> %d\n", available, width.Resolve(available, 0))
	}
}
Output:
available  20 -> 24
available  40 -> 36
available 100 -> 60

func Cells

func Cells(n int) Extent

Cells is a fixed number of cells.

func ExtentFunc

func ExtentFunc(f func(available int) int) Extent

ExtentFunc builds an extent from a plain function of the available room.

func Fit

func Fit(measure func(cross int) int) Extent

Fit is content-driven: the measure is handed the extent already resolved for the other axis — the width, when Fit is used for a height — and answers how many cells the content needs.

func Frac

func Frac(num, den int) Extent

Frac is a fraction of the available room.

func Share

func Share(percent int) Extent

Share is a percentage of the available room.

func (Extent) AtLeast

func (e Extent) AtLeast(n int) Extent

AtLeast floors the extent.

func (Extent) AtMost

func (e Extent) AtMost(n int) Extent

AtMost caps the extent.

func (Extent) Clamp

func (e Extent) Clamp(lo, hi int) Extent

Clamp bounds the extent on both sides.

func (Extent) Minus

func (e Extent) Minus(n int) Extent

Minus subtracts n cells.

func (Extent) Plus

func (e Extent) Plus(n int) Extent

Plus adds n cells.

func (Extent) Resolve

func (e Extent) Resolve(available, cross int) int

Resolve computes the extent. cross is the already-resolved size of the other axis, which only Fit looks at.

func (Extent) Zero

func (e Extent) Zero() bool

Zero reports whether the extent says nothing, in which case the node's own measured minimum is used.

type Float

type Float struct {
	// ID names the float. It overrides the node's own ID when set.
	ID ID
	// Node is what to draw.
	Node Node
	// Anchor decides where it goes. The zero value centres it.
	Anchor Anchor
	// Size is how big it is. A zero extent means the node's measured minimum.
	Size FloatSize
	// Margin keeps the float away from the edges of its container.
	Margin Padding
	// Z raises it above the tree. Zero means one level up, which is what a
	// dialog over an app wants.
	Z int
	// Modal captures input: clicks outside it report [Hit.Blocked].
	Modal bool
	// Clamp decides what happens when the float does not fit where it was
	// asked to go. The zero value keeps it on screen.
	Clamp Clamping
}

Float is a node placed over the layout rather than inside it: a dialog, a context menu, a corner spinner, a tooltip.

Floats are resolved after the tree they hang off, in declaration order, so an AnchorTo can refer to anything already placed.

Example

A float is placed over the layout and clamped to it: flipped to the other side of its anchor when it would overflow, then shifted, then trimmed. A context menu opened at the edge of the screen therefore stays on it.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	menu := lattice.Float{
		ID:   "menu",
		Node: lattice.Leaf(""),
		Size: lattice.FloatSize{W: lattice.Cells(14), H: lattice.Cells(5)},
	}

	for _, click := range []lattice.Position{{X: 4, Y: 2}, {X: 38, Y: 18}} {
		menu.Anchor = lattice.AnchorPoint(click, lattice.GravityTopLeft)
		g := lattice.MustSolve(
			lattice.Leaf("body").Float(menu),
			lattice.R(0, 0, 40, 20),
		)
		r, _ := g.Rect("menu")
		fmt.Printf("click (%2d,%2d) -> menu %v\n", click.X, click.Y, r)
	}
}
Output:
click ( 4, 2) -> menu (4,2)-(18,7)
click (38,18) -> menu (24,13)-(38,18)

type FloatSize

type FloatSize struct{ W, H Extent }

FloatSize is a float's size, each axis given as an Extent.

type Geometry

type Geometry struct {
	// contains filtered or unexported fields
}

Geometry is the result of a solve: every node's absolute rectangle, in a form that is safe to keep in a Bubble Tea value model. It is pure data — store it, copy it, compare it.

Every coordinate it exposes is absolute. There is no parent-relative getter, which is why nothing downstream has to probe the screen cell by cell to recover where a panel actually is.

func MustSolve

func MustSolve(root Node, area Rect) *Geometry

MustSolve is Solve for tests and examples: it panics instead of returning the programmer error.

func Solve

func Solve(root Node, area Rect) (*Geometry, error)

Solve turns a declared tree into absolute geometry.

It runs depth-first and top-down, in absolute coordinates throughout. Errors are reserved for programmer mistakes — duplicate IDs, empty containers, negative gaps — because no screen size can fix those. Everything that is merely too small to work is a Diagnostic on the returned geometry, so a cramped terminal degrades instead of crashing.

Solve applies no sizes and touches nothing outside the returned value. Call it exactly once per Update, never in View.

func (*Geometry) Apply

func (g *Geometry) Apply() []Diagnostic

Apply hands every bound node its content size and returns whatever went wrong.

Solve deliberately does not do this: solving must be free of side effects so tests can solve a thousand sizes without touching a model. Apply is the separate, explicit step — and it is single-shot. Once it has run, the geometry forgets its sizers, so the copy kept in a Bubble Tea model stays what it claims to be: pure data with no pointers into a model value that has since been replaced.

func (*Geometry) Area

func (g *Geometry) Area() Rect

Area is the rectangle the tree was solved into.

func (*Geometry) Content

func (g *Geometry) Content(id ID) (Rect, bool)

Content returns the rectangle inside a node's chrome and padding — where its contents may paint and where its children were laid out.

func (*Geometry) Degraded

func (g *Geometry) Degraded() bool

Degraded reports whether the layout differs from what was declared because it did not fit.

func (*Geometry) Diagnostics

func (g *Geometry) Diagnostics() []Diagnostic

Diagnostics reports everything the solve did that the author probably did not intend. An empty slice is the goal; tests should assert on it.

Example

Diagnostics are data, not failures. A layout too small for what it declared degrades and says so, in codes a test can assert on.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	panel := func(id lattice.ID, priority int) lattice.Cell {
		return lattice.At(lattice.Fill(1), lattice.Leaf(id).
			MinSize(10, 5).
			Priority(priority))
	}
	tree := lattice.Col("root", panel("keep", 2), panel("drop-me", 1))

	g := lattice.MustSolve(tree, lattice.R(0, 0, 20, 6))
	for _, d := range g.Diagnostics() {
		fmt.Println(d.Code, "on", d.ID)
	}
	fmt.Println("drop-me visible:", g.Visible("drop-me"))
	fmt.Println("degraded:", g.Degraded())
}
Output:
Undersized on root
Dropped on root
drop-me visible: false
degraded: true

func (*Geometry) Divider

func (g *Geometry) Divider(container ID, index int) (Divider, bool)

Divider returns one container's divider by index.

func (*Geometry) Dump

func (g *Geometry) Dump() string

Dump renders the solved tree as an indented, ANSI-free listing with absolute rectangles. It is the primary golden-file artifact: stable, readable, and it diffs into exactly the line that moved.

func (*Geometry) Has

func (g *Geometry) Has(id ID) bool

Has reports whether the geometry contains a node with this ID.

func (*Geometry) Hit

func (g *Geometry) Hit(x, y int) Hit

Hit reports the topmost hittable node at an absolute screen position.

The scan is a linear pass over the nodes in reverse draw order, which for the sizes a terminal layout ever reaches is faster than any index would be — and unlike probing a compositor cell by cell, it gives back the node itself rather than a rectangle to subtract from.

Example

A hit answers everything mouse routing needs at once: which node, which row of its content, and whether the point was on the border.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	tree := lattice.Col("root",
		lattice.At(lattice.Len(1), lattice.Leaf("topbar")),
		lattice.At(lattice.Fill(1), lattice.Leaf("list").
			Chrome(lattice.Chrome{Border: lattice.Rounded()})),
	)
	g := lattice.MustSolve(tree, lattice.R(0, 0, 40, 10))

	for _, p := range []lattice.Position{{X: 3, Y: 0}, {X: 3, Y: 4}, {X: 0, Y: 4}} {
		h := g.HitAt(p)
		fmt.Printf("(%d,%d) -> %-7s row %2d  in content: %v  path %v\n",
			p.X, p.Y, h.ID(), h.Row(), h.InContent(), h.Path())
	}
}
Output:
(3,0) -> topbar  row  0  in content: true  path [root topbar]
(3,4) -> list    row  2  in content: true  path [root list]
(0,4) -> list    row  2  in content: false  path [root list]

func (*Geometry) HitAt

func (g *Geometry) HitAt(p Position) Hit

HitAt is Geometry.Hit taking a position.

func (*Geometry) IDs

func (g *Geometry) IDs() []ID

IDs lists every node's ID in declaration order, root first. Anonymous nodes appear under their synthetic "#N" IDs.

func (*Geometry) Owner

func (g *Geometry) Owner(x, y int) ID

Owner reports which node owns a cell — the same answer Geometry.Hit gives, ignoring whether the node opted out of hit testing.

func (*Geometry) Rect

func (g *Geometry) Rect(id ID) (Rect, bool)

Rect returns a node's own rectangle, borders and all. ok is false when no node has that ID.

func (*Geometry) Root

func (g *Geometry) Root() View

Root returns the root node's view. It is always present: a solve either returns an error or a geometry with at least the root in it.

func (*Geometry) Shape

func (g *Geometry) Shape() uint64

Shape is a structural hash of the solve: IDs, kinds, constraints, insets and visibility, but not sizes. Two trees with the same shape can be substituted for one another at render time; two that differ cannot, and that difference is a bug worth shouting about.

func (*Geometry) Size

func (g *Geometry) Size(id ID) (w, h int, ok bool)

Size returns a node's content size: exactly what the component inside it should be told to be. This is the replacement for hand-written panelContentWidth/panelContentHeight helpers.

func (*Geometry) TooSmall

func (g *Geometry) TooSmall() (want Size, ok bool)

TooSmall reports whether the area is below the root's Node.MinScreen, and what it would take. Renderers draw a notice instead of a mangled layout.

func (*Geometry) View

func (g *Geometry) View(id ID) (View, bool)

View returns a richer handle on a node.

func (*Geometry) Visible

func (g *Geometry) Visible(id ID) bool

Visible reports whether the node was laid out and should be drawn. A hidden node, or one with no room for its chrome, is present in the geometry but not visible.

type Gravity

type Gravity int

Gravity says which corner of the float lands on an anchor point.

const (
	GravityTopLeft Gravity = iota
	GravityTopRight
	GravityBottomLeft
	GravityBottomRight
)

type Hit

type Hit struct {
	// contains filtered or unexported fields
}

Hit is the result of asking which node is at a point on screen.

It answers in one step everything mouse routing used to reconstruct by hand: which node, where inside it, which row of its content, whether the click landed on the border, and whether a modal is swallowing it.

func (Hit) Blocked

func (h Hit) Blocked() bool

Blocked reports that a modal float is up and the point missed it. It replaces the chain of "is this dialog active, is that one" guards at the top of every mouse handler.

func (Hit) Col

func (h Hit) Col() int

Col is the content-relative column.

func (Hit) Content

func (h Hit) Content() Rect

Content is the node's content rectangle.

func (Hit) Divider

func (h Hit) Divider() (Divider, bool)

Divider is the movable edge the point landed on. ok is false when it landed on none.

if hit := g.Hit(x, y); hit.OnDivider() {
    m.drag, _ = hit.Divider()
}

func (Hit) Empty

func (h Hit) Empty() bool

Empty reports whether the point landed on nothing.

func (Hit) Has

func (h Hit) Has(id ID) bool

Has reports whether id is anywhere on the hit's path.

func (Hit) ID

func (h Hit) ID() ID

ID is the node the point landed on.

func (Hit) InContent

func (h Hit) InContent() bool

InContent reports whether the point landed inside the content rather than on the node's border or padding.

func (Hit) Local

func (h Hit) Local() Position

Local is the position relative to the node's content rectangle. It is negative on the border.

func (Hit) OnDivider

func (h Hit) OnDivider() bool

OnDivider reports whether the point landed on a movable edge of a Node.Resizable container. It is answered alongside Hit.ID rather than instead of it, because those cells are a panel's frame as well as a handle.

func (Hit) Path

func (h Hit) Path() []ID

Path is the chain of nodes containing the point, root first. Use it to bubble an event up until something handles it.

func (Hit) Point

func (h Hit) Point() Position

Point is the absolute position that was tested.

func (Hit) Rect

func (h Hit) Rect() Rect

Rect is the node's rectangle, borders included.

func (Hit) Row

func (h Hit) Row() int

Row is the content-relative row, which for a list panel is the item index.

func (Hit) View

func (h Hit) View() (View, bool)

View returns the node's view.

type ID

type ID string

ID names a node. IDs are how everything downstream — geometry lookups, hit tests, size application, painters — refers back to a declaration, so they should be stable across frames. Duplicate non-empty IDs are a programmer error and Solve rejects them.

An empty ID is allowed for structural nodes nobody needs to address; the solver gives those a synthetic "#N" ID so that every node in a Geometry remains reachable for dumps and tests. Do not depend on synthetic IDs: they shift when the tree's shape changes.

type Justify

type Justify int

Justify distributes surplus space in a container whose children do not consume the whole extent. It is the justify-content analogue.

const (
	// JustifyStart leaves the surplus at the trailing edge.
	JustifyStart Justify = iota
	// JustifyEnd leaves the surplus at the leading edge.
	JustifyEnd
	// JustifyCentre splits the surplus evenly before and after.
	JustifyCentre
	// JustifySpaceBetween puts equal gaps between children and none outside.
	JustifySpaceBetween
	// JustifySpaceEvenly makes every gap, including the outer two, equal.
	JustifySpaceEvenly
	// JustifySpaceAround gives every child equal space on both sides.
	JustifySpaceAround
	// JustifyFill hands the surplus to the lowest-priority trailing child, so
	// the children always cover the whole extent.
	JustifyFill
)

func (Justify) String

func (j Justify) String() string

type Kind

type Kind int

Kind is what a node does with its rectangle.

const (
	// KindLeaf owns its rectangle outright and has no children.
	KindLeaf Kind = iota
	// KindRow splits its content rectangle left to right.
	KindRow
	// KindCol splits its content rectangle top to bottom.
	KindCol
	// KindStack gives every child the whole content rectangle, z-ordered.
	KindStack
)

func (Kind) String

func (k Kind) String() string

type Node

type Node struct {
	// contains filtered or unexported fields
}

Node is one rectangle in a layout tree. It is an immutable value: every modifier returns a copy, so a node can be shared, stored and re-declared each frame without aliasing surprises.

A tree is declared with Leaf, Row, Col and Stack, and solved with Solve. Declaring a tree allocates no geometry and performs no arithmetic.

func Col

func Col(id ID, cells ...Cell) Node

Col splits its content rectangle top to bottom, in declaration order.

func Dock

func Dock(id ID, d Docked) Node

Dock is sugar for the shape almost every application has: bars pinned to the edges of the screen and everything else in the middle.

lattice.Dock("root", lattice.Docked{
    Top:    []lattice.Cell{lattice.At(lattice.Len(1), topBar)},
    Bottom: []lattice.Cell{lattice.At(lattice.Len(1), footer)},
    Left:   []lattice.Cell{lattice.At(lattice.Len(24), sidebar)},
    Centre: body,
})

The bars are ordinary cells in an ordinary column and row — there is no separate concept to learn, and no "height minus the footer" left to get wrong. Declaring nothing but a Centre gives back the Centre itself.

Example

Dock is sugar for bars pinned to the edges with everything else in the middle. It builds ordinary rows and columns — there is no separate concept, and no "height minus the footer" left to get wrong.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	tree := lattice.Dock("root", lattice.Docked{
		Top:    []lattice.Cell{lattice.At(lattice.Len(1), lattice.Leaf("topbar"))},
		Bottom: []lattice.Cell{lattice.At(lattice.Len(1), lattice.Leaf("footer"))},
		Left:   []lattice.Cell{lattice.At(lattice.Len(20), lattice.Leaf("sidebar"))},
		Centre: lattice.Leaf("body"),
	})

	g := lattice.MustSolve(tree, lattice.R(0, 0, 60, 12))
	for _, id := range []lattice.ID{"topbar", "sidebar", "body", "footer"} {
		r, _ := g.Rect(id)
		fmt.Printf("%-8s %v\n", id, r)
	}
}
Output:
topbar   (0,0)-(60,1)
sidebar  (0,1)-(20,11)
body     (20,1)-(60,11)
footer   (0,11)-(60,12)

func Leaf

func Leaf(id ID) Node

Leaf is a node with no children. It is where content goes.

func Row

func Row(id ID, cells ...Cell) Node

Row splits its content rectangle left to right, in declaration order.

func Stack

func Stack(id ID, layers ...Node) Node

Stack gives every layer the parent's whole content rectangle. Layers are drawn in declaration order, then by Node.Z; later layers sit on top.

func (Node) Bind

func (n Node) Bind(s Sizer) Node

Bind attaches a sizer, so the component inside this node is told the node's content size whenever Geometry.Apply runs.

func (Node) Chrome

func (n Node) Chrome(c Chrome) Node

Chrome frames the node: border, titles, padding, background. The content rectangle shrinks to fit inside it, and a node whose rectangle cannot hold its chrome is not drawn at all — a panel is whole or absent, never a three-sided box.

func (Node) Collapse

func (n Node) Collapse(c Collapse) Node

Collapse says what should happen to this node when its container runs out of room. The default is CollapseDrop.

func (Node) CollapseBorders

func (n Node) CollapseBorders() Node

CollapseBorders makes the container's adjacent children share the border between them: they overlap by exactly one cell, one panel's frame is drawn over the other's, and the cells where runs meet become the tee or cross their neighbours imply.

lattice.Row("body",
    lattice.At(lattice.Fill(35), files),
    lattice.At(lattice.Fill(65), detail),
).CollapseBorders()

It is the one place the no-overlap invariant is relaxed, and it is relaxed visibly: the shared run is recorded on the container (View.Shared) and every cell still has exactly one owner (View.Owns), so a click on a shared border belongs to one panel and to one panel only.

Collapsing is a property of the container because a container is what knows its children are adjacent. Which pairs actually share is worked out per solve, from the children that survived hiding and degradation, so hiding a panel cannot leave its neighbour with a dropped side and no neighbour to justify it.

A shared run is drawn once, by whichever of the two panels draws last: the higher Node.Z first, then the later declaration. So a panel that is highlighted — focused, selected, in error — wants raising while it is, or the runs it shares stay in its neighbours' style and it keeps one edge of an otherwise highlighted frame in the wrong colour:

panel := lattice.Leaf("commits").Chrome(chrome)
if focused {
    panel = panel.Z(1)
}

Raising it wins it the run without taking it out of the picture: it goes on meeting its neighbours in tees rather than closing itself off in corners.

A pair shares its edge only when both sides bring a border to it — a child with no frame on the shared side, or one marked Node.Detached, keeps the ordinary edge. So does every pair in a container with a Node.Gap: there is nothing to share when the neighbours do not touch.

func (Node) Detached

func (n Node) Detached() Node

Detached keeps this child out of its container's border collapsing, on both sides. Use it where a gap is wanted in a container that otherwise shares its edges.

func (Node) Float

func (n Node) Float(fs ...Float) Node

Float attaches floating nodes. They are drawn over this node's subtree and clipped to its content rectangle — attach them to the root and they are clipped to the screen.

func (Node) Gap

func (n Node) Gap(cells int) Node

Gap puts n cells between adjacent children. Negative gaps are rejected by Solve: the solver would happily overlap children, which breaks the no-overlap invariant the whole library rests on.

func (Node) Hidden

func (n Node) Hidden(hidden bool) Node

Hidden excludes the node from the solve entirely: it occupies no space and its siblings take the room. The node and its subtree still appear in the geometry, with empty rectangles and Visible reporting false, so a conditional panel is one declaration rather than two branches.

Example

A conditional panel is one declaration, not a branch in two places. A hidden node takes no space and its siblings get the room, but it stays in the geometry so its ID keeps resolving.

package main

import (
	"fmt"

	"github.com/kondr1/lattice"
)

func main() {
	tree := func(showDetail bool) lattice.Node {
		return lattice.Row("body",
			lattice.At(lattice.Fill(1), lattice.Leaf("list")),
			lattice.At(lattice.Fill(1), lattice.Leaf("detail").Hidden(!showDetail)),
		)
	}

	for _, show := range []bool{true, false} {
		g := lattice.MustSolve(tree(show), lattice.R(0, 0, 40, 10))
		w, _, _ := g.Size("list")
		fmt.Printf("detail shown %-5v  list is %d wide, detail visible: %v\n",
			show, w, g.Visible("detail"))
	}
}
Output:
detail shown true   list is 20 wide, detail visible: true
detail shown false  list is 40 wide, detail visible: false

func (Node) Hittable

func (n Node) Hittable(hittable bool) Node

Hittable controls whether hit tests can land on this node. Structural containers are usually left hittable; a decorative overlay is not.

func (Node) ID

func (n Node) ID() ID

ID reports the node's declared ID. It is empty for anonymous nodes; the synthetic ID a solve assigns is visible only through the resulting Geometry.

func (Node) Justify

func (n Node) Justify(j Justify) Node

Justify distributes surplus space among the children. The default, JustifyStart, leaves the surplus at the trailing edge — and reports it as a CodeUnusedSpace diagnostic, which usually means a missing Fill(1).

func (Node) Kind

func (n Node) Kind() Kind

Kind reports what the node does with its rectangle.

func (Node) MaxSize

func (n Node) MaxSize(w, h int) Node

MaxSize caps the node's rectangle, keeping its top-left corner. Space beyond the cap is left unpainted, so a capped child no longer tiles its parent.

func (Node) MinScreen

func (n Node) MinScreen(w, h int) Node

MinScreen declares the smallest screen the layout is meant for. Below it, Geometry.TooSmall reports and the renderer draws a "needs 80×24" notice instead of a mangled layout. It applies to the root node only.

func (Node) MinSize

func (n Node) MinSize(w, h int) Node

MinSize declares the smallest useful size for the node. It does not force the solver's hand; it is what Solve measures against to decide that a node is undersized, and what the degradation pass uses to decide what to drop.

func (Node) Pad

func (n Node) Pad(p Padding) Node

Pad insets the node's content rectangle. Children are laid out inside the padding; the node's own rectangle is unchanged.

func (Node) Paint

func (n Node) Paint(p Painter) Node

Paint attaches the thing that draws the node's contents. The painter is handed a Surface clipped to the content rectangle, so it cannot draw outside its node however hard it tries — and it is given no way to resize anything, so the "component resized inside View" bug cannot be written.

func (Node) PaintString

func (n Node) PaintString(f func(w, h int) string) Node

PaintString draws a pre-rendered string, which the node clips but does not re-style. This is the escape hatch for content already built with lipgloss.

func (Node) Priority

func (n Node) Priority(p int) Node

Priority ranks the node against its siblings when the container has to drop children to fit. Lower priority is dropped first; ties break on declaration order, last declared first.

func (Node) Replace

func (n Node) Replace(id ID, fn func(Node) Node) Node

Replace returns a copy of the tree with fn applied to the node named id. Trees are values, so this rewrites nothing in place; it is how a caller — or a test — swaps one node out of an otherwise identical declaration.

func (Node) Resizable

func (n Node) Resizable(s *Split) Node

Resizable marks the container's internal edges as draggable and hands it the split its children are sized by.

The split must have one weight per declared cell — Solve rejects a mismatch as a programmer error, because a divider that moves a weight nothing reads is worse than one that does not move.

lattice.Row("body",
    lattice.At(split.At(0), files),
    lattice.At(split.At(1), detail),
).Resizable(split)

The solver then records which cells each divider occupies, and a hit on them reports Hit.OnDivider.

func (Node) Tail

func (n Node) Tail(s string) Node

Tail is appended to text the node has to cut short. The default is to cut with no marker.

func (Node) Wrap

func (n Node) Wrap(wrap bool) Node

Wrap makes the node's text wrap to its width. The default is false: content is clipped. Wrapping is what turns one over-long row into an extra line, which is what pushes a panel's own border off the bottom of its slot.

func (Node) Z

func (n Node) Z(z int) Node

Z raises the node in the draw order relative to its siblings. Within one z level, declaration order decides.

type Padding

type Padding struct{ Top, Right, Bottom, Left int }

Padding is an inset measured in cells, in CSS order.

func Pad

func Pad(sides ...int) Padding

Pad builds a Padding from a variable number of sides, following the CSS shorthand convention:

  • 0 args: no padding.
  • 1 arg: uniform on every side.
  • 2 args: vertical, horizontal.
  • 3 args: top, horizontal, bottom.
  • 4 args: top, right, bottom, left.

Any other count panics: it is a declaration-time programmer error.

func (Padding) Add

func (p Padding) Add(q Padding) Padding

Add returns the sum of two paddings, side by side.

func (Padding) Apply

func (p Padding) Apply(r Rect) Rect

Apply insets r by p. The result is never larger than r and never has a negative extent: when the padding does not fit, the rectangle collapses at its own top-left corner rather than relocating to the origin — the trap in layout.Padding.

func (Padding) Empty

func (p Padding) Empty() bool

Empty reports whether the padding insets nothing.

func (Padding) Horizontal

func (p Padding) Horizontal() int

Horizontal is the total inset along the x axis.

func (Padding) Vertical

func (p Padding) Vertical() int

Vertical is the total inset along the y axis.

type PaintFunc

type PaintFunc func(*Surface)

PaintFunc adapts a function to Painter.

func (PaintFunc) Paint

func (f PaintFunc) Paint(s *Surface)

Paint implements Painter.

type Painter

type Painter interface{ Paint(s *Surface) }

Painter draws a node's contents.

It receives a Surface and nothing else: no screen, no rectangle it could escape, and no handle on anything it could resize. Sizing components belongs to the update path, and a painter is given no way to do it.

type Position

type Position = uv.Position

Position is a point in absolute screen coordinates. It is an alias for image.Point.

type Rect

type Rect = uv.Rectangle

Rect is a rectangle in absolute screen coordinates. It is an alias for image.Rectangle, so Intersect, Union, Overlaps, Inset, In and Add are all available on it.

func R

func R(x, y, w, h int) Rect

R builds a rectangle from a position and a size. Note the width/height semantics: R(2, 3, 10, 4) is ten cells wide and four tall, starting at (2,3).

type RenderOption

type RenderOption func(*renderOptions)

RenderOption configures a render.

func WithStrict

func WithStrict(strict bool) RenderOption

WithStrict makes a shape mismatch between the solved geometry and the tree handed to the renderer panic instead of re-solving. Turn it on in tests.

func WithTooSmall

func WithTooSmall(f func(area Rect, want Size) string) RenderOption

WithTooSmall replaces the notice drawn when the screen is below the root's Node.MinScreen.

type Severity

type Severity int

Severity ranks a diagnostic.

const (
	// SeverityInfo is worth knowing but not wrong: a dropped low-priority
	// child on a small screen, for instance.
	SeverityInfo Severity = iota
	// SeverityWarn is a layout that will render but not as declared.
	SeverityWarn
	// SeverityError is a layout that cannot render correctly at all.
	SeverityError
)

func (Severity) String

func (s Severity) String() string

type Side

type Side int

Side names which side of another node a float sits on.

const (
	SideTop Side = iota
	SideRight
	SideBottom
	SideLeft
)

type Size

type Size struct{ W, H int }

Size is a width/height pair. It is used where a rectangle's position is irrelevant — minima, maxima and "how much room was wanted" diagnostics.

func SizeOf

func SizeOf(r Rect) Size

SizeOf returns the size of r.

func (Size) Empty

func (s Size) Empty() bool

Empty reports whether the size covers no cells.

func (Size) String

func (s Size) String() string

type Sizer

type Sizer interface{ SetContentSize(w, h int) }

Sizer receives a node's content size. It is the one direction in which lattice talks to the components inside it: the layout decides how big a panel is, and the panel's component is told.

bubbles has no layout of its own — every component is imperative SetWidth/SetHeight/SetSize on a pointer receiver — so something has to make that call. Doing it here means it happens once, in the update path, from the same numbers the renderer will use.

type SizerFunc

type SizerFunc func(w, h int)

SizerFunc adapts a function to Sizer.

Every adapter in lattice/sizers is built on this, which is what makes the render-path guard universal: a sizer invoked while a frame is being painted records a diagnostic instead of resizing, because a resize in the render path is discarded by Bubble Tea's value semantics and would only look like it worked.

That guard is process-wide, because Go has no goroutine-local state to hang it on. Solving, applying and rendering one layout from one goroutine — which is what Bubble Tea does — is therefore the supported arrangement. Painting one layout while a second is being applied on another goroutine would refuse the second one's resizes and report CodeSizedDuringPaint against them.

func (SizerFunc) SetContentSize

func (f SizerFunc) SetContentSize(w, h int)

SetContentSize implements Sizer.

type Split

type Split struct {
	// contains filtered or unexported fields
}

Split is a proportion between sibling cells that can be moved at runtime.

It holds weights, exactly as Fill takes them, and hands them out as constraints:

split := lattice.NewSplit(35, 65)

lattice.Row("body",
    lattice.At(split.At(0), files),
    lattice.At(split.At(1), detail),
).Resizable(split)

The tree is a value and is re-declared every frame, so Split.At is read afresh on each declaration: moving a divider changes the Split, and the next solve sees it. A Split is safe for concurrent use, and holding one is how an application keeps pane sizes across a restart — see Split.MarshalJSON.

func NewSplit

func NewSplit(weights ...int) *Split

NewSplit builds a split from weights, in the same terms Fill takes them: NewSplit(35, 65) gives the first cell just over a third.

The weights are normalized, so what comes back out of Split.Weights is proportional to what went in rather than equal to it.

func (*Split) At

func (s *Split) At(i int) Constraint

At is the constraint for one cell. Read it in the declaration — the value is the split as it stands now, and the next declaration will read it again.

func (*Split) Len

func (s *Split) Len() int

Len is how many cells the split sizes.

func (*Split) MarshalJSON

func (s *Split) MarshalJSON() ([]byte, error)

MarshalJSON writes the split as an array of weights in their smallest whole terms — [35,65] — which is what an application puts in its configuration file beside the theme and the open repositories.

func (*Split) Set

func (s *Split) Set(weights ...int)

Set replaces every weight, normalizing as NewSplit does. The number of weights must go on matching the number of cells the container declares; Solve reports a mismatch as a programmer error.

func (*Split) String

func (s *Split) String() string

String is the split as a ratio, in its smallest whole terms: "35:65".

func (*Split) UnmarshalJSON

func (s *Split) UnmarshalJSON(b []byte) error

UnmarshalJSON reads the weights back. Any proportional set of numbers gives the same layout, so a hand-edited [7,13] is as good as the [35,65] it was written from.

func (*Split) Weight

func (s *Split) Weight(i int) int

Weight is one cell's weight, normalized. Out of range, it is zero.

func (*Split) Weights

func (s *Split) Weights() []int

Weights is a copy of every weight, normalized.

type Surface

type Surface struct {
	// contains filtered or unexported fields
}

Surface is what a painter draws on. Its coordinates start at (0,0) in the top-left of the node's content rectangle, and every write is clipped to that rectangle — a painter cannot reach outside its node, whatever it is handed.

That is the difference between "the panel is exactly its slot" being a guarantee and being documentation. lipgloss cannot enforce a box: Width wraps instead of clipping, Height only pads, and MaxWidth/MaxHeight cut through the border because they run after it. A Surface writes cells, so overflow costs content and never the frame.

Surface implements uv.Screen in its own local coordinates, so any uv.Drawable — including a whole lipgloss.Canvas — can be drawn onto it.

func (*Surface) Block

func (s *Surface) Block(str string)

Block draws multi-line text from the surface's origin, one line per row, clipped on both axes. Lines are not wrapped unless the node opted in with Node.Wrap.

func (*Surface) BlockAt

func (s *Surface) BlockAt(r Rect, str string)

BlockAt draws multi-line text into a sub-rectangle of the surface.

func (*Surface) Bounds

func (s *Surface) Bounds() Rect

Bounds is the surface's own rectangle, always anchored at (0,0).

func (*Surface) CellAt

func (s *Surface) CellAt(x, y int) *uv.Cell

CellAt implements uv.Screen. It returns nil outside the clip.

func (*Surface) Drawable

func (s *Surface) Drawable(d uv.Drawable, r Rect)

Drawable draws any uv.Drawable into r — a lipgloss.Canvas, a uv.Buffer, a component that already knows how to render itself. This is the escape hatch that keeps the clipping guarantee from being a cage.

func (*Surface) Fill

func (s *Surface) Fill(c uv.Cell)

Fill paints every cell of the surface with c.

func (*Surface) FillRect

func (s *Surface) FillRect(r Rect, c uv.Cell)

FillRect paints every cell of r with c.

func (*Surface) SetCell

func (s *Surface) SetCell(x, y int, c *uv.Cell)

SetCell implements uv.Screen. Writes outside the clip are dropped.

func (*Surface) Size

func (s *Surface) Size() (w, h int)

Size is the surface's nominal size in cells: the size the painter was promised, whether or not all of it is currently on screen.

func (*Surface) String

func (s *Surface) String(x, y int, str string)

String draws one line of styled text at (x, y), truncated at the surface's right edge. It paints exactly the cells the text covers and no more, so a short line on a transparent node leaves the rest of the row untouched.

func (*Surface) Sub

func (s *Surface) Sub(r Rect) *Surface

Sub returns a surface covering r, with its own origin at r's top-left. Writes through it are clipped to r as well as to everything r is already inside.

func (*Surface) Tail

func (s *Surface) Tail() string

Tail reports the string appended to text this surface has to truncate.

func (*Surface) WidthMethod

func (s *Surface) WidthMethod() uv.WidthMethod

WidthMethod implements uv.Screen.

func (*Surface) WrapBlock

func (s *Surface) WrapBlock(str string)

WrapBlock draws multi-line text, wrapping every line to the surface's width.

type Title

type Title struct {
	Text  string
	Align Align
	// Inset is how many cells from the corner the title starts. Zero means
	// [DefaultTitleInset]; a negative value means flush against the corner.
	Inset int
	Style lipgloss.Style
	// Tail is appended when the title has to be cut. Empty means "…".
	Tail string
}

Title is text spliced into a border run. It is not a separate row: a titled panel is exactly as tall as an untitled one.

type View

type View struct {
	// contains filtered or unexported fields
}

View is a handle on one solved node. It is a value; holding one keeps the geometry alive but changes nothing.

func (View) Border

func (v View) Border() Padding

Border is how many cells of the node's rectangle its frame occupies on each side. It is what every hand-written "subtract two" was reaching for.

func (View) Children

func (v View) Children() []ID

Children lists the node's children in declaration order.

func (View) Col

func (v View) Col(x int) int

Col converts an absolute x to a content-relative column.

func (View) Collapses

func (v View) Collapses() bool

Collapses reports whether the node shares the borders between its children.

func (View) Content

func (v View) Content() Rect

Content is the rectangle inside the node's chrome and padding, absolute.

func (View) Depth

func (v View) Depth() int

Depth is the node's distance from the root.

func (View) Dividers

func (v View) Dividers() []Rect

Dividers lists the movable edges of a resizable container, in order.

func (View) Hittable

func (v View) Hittable() bool

Hittable reports whether hit tests may land on this node.

func (View) ID

func (v View) ID() ID

ID is the node's ID, synthetic if the node was declared anonymous.

func (View) IsFloat

func (v View) IsFloat() bool

IsFloat reports whether the node was placed as a Float — over the layout rather than in it, so it neither tiles its parent nor avoids its siblings.

func (View) Kind

func (v View) Kind() Kind

Kind is what the node does with its rectangle.

func (View) Local

func (v View) Local(p Position) Position

Local converts an absolute position to one relative to the node's content rectangle — which is the coordinate system its painter and its component think in.

func (View) Min

func (v View) Min() Size

Min is the smallest size the node measured out to: its children's minima plus its own insets, floored by its declared MinSize.

func (View) Owns

func (v View) Owns(x, y int) bool

Owns reports whether this node is the one responsible for painting a cell.

Every cell of the screen has exactly one owner, shared borders included: where two panels overlap by a border run, the one that draws last is the one that shows, and it is the one that owns those cells. That is what keeps "the panels overlap by a cell" from meaning "nobody knows who this cell belongs to" — and it is the same answer Geometry.Hit gives a mouse click.

func (View) Parent

func (v View) Parent() (ID, bool)

Parent returns the parent's ID. ok is false at the root.

func (View) Rect

func (v View) Rect() Rect

Rect is the node's own rectangle, absolute.

func (View) Row

func (v View) Row(y int) int

Row converts an absolute y to a content-relative row. This is the whole of the hand-written "y - bounds.Min.Y - borderTop" arithmetic, with the border supplied by the node's own chrome instead of a package constant.

func (View) Shared

func (v View) Shared() []Rect

Shared returns the one-cell runs this container's children share, in the order the children were declared. It is empty for everything but a container with Node.CollapseBorders and room to honour it.

A shared run is the one place two rectangles in the tree overlap, and it is recorded rather than inferred so that nothing downstream has to work out where the overlaps are: they are the cells a divider would be dragged by, the cells View.Owns arbitrates, and the exception the no-overlap assertion allows.

func (View) Size

func (v View) Size() Size

Size is the content size — what a component inside this node should be.

func (View) Titles

func (v View) Titles() []Rect

Titles returns the cells the node's spliced titles occupy. They sit inside the border runs, so those cells are frame rather than content — and a title containing a space puts a legitimate blank in the middle of an intact border.

func (View) Valid

func (v View) Valid() bool

Valid reports whether the view refers to a node.

func (View) Visible

func (v View) Visible() bool

Visible reports whether the node should be drawn.

func (View) Z

func (v View) Z() int

Z is the node's draw-order level.

Directories

Path Synopsis
examples
borderbug command
Command borderbug is a minimal reproduction of the ultraviolet trap that made styled borders disappear.
Command borderbug is a minimal reproduction of the ultraviolet trap that made styled borders disappear.
dashboard command
Command dashboard is a runnable application in the shape lattice was built for: edge bars, a fixed-width sidebar, a split main area, a panel that can be hidden, a modal dialog and a context menu — and not one line of layout arithmetic.
Command dashboard is a runnable application in the shape lattice was built for: edge bars, a fixed-width sidebar, a split main area, a panel that can be hidden, a modal dialog and a context menu — and not one line of layout arithmetic.
floatflip command
Command floatflip is a minimal reproduction of the anchor-flipping bug: a float that had to flip on both axes lost the first flip.
Command floatflip is a minimal reproduction of the anchor-flipping bug: a float that had to flip on both axes lost the first flip.
rendercost command
Command rendercost measures the difference between the two ways of getting a panel's cells onto the frame.
Command rendercost measures the difference between the two ways of getting a panel's cells onto the frame.
internal
paint
Package paint holds the cell-level primitives the renderer is built from: turning a styled string into cells, measuring it, and truncating it.
Package paint holds the cell-level primitives the renderer is built from: turning a styled string into cells, measuring it, and truncating it.
Package latticetest turns lattice's invariants into assertions.
Package latticetest turns lattice's invariants into assertions.
Package sizers adapts bubbles components to lattice's lattice.Sizer.
Package sizers adapts bubbles components to lattice's lattice.Sizer.
Package teax is lattice's Bubble Tea glue: one object that owns the terminal size, solves the layout at the end of every Update, renders it in View, and routes mouse events back to the node they landed on.
Package teax is lattice's Bubble Tea glue: one object that owns the terminal size, solves the layout at the end of every Update, renders it in View, and routes mouse events back to the node they landed on.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址