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 ¶
- Constants
- func DefaultTooSmall(area Rect, want Size) string
- func Render(g *Geometry, tree Node, opts ...RenderOption) string
- type Align
- type Anchor
- type Background
- type Border
- type Cell
- type Chrome
- type Clamping
- type Code
- type Collapse
- type Constraint
- type Corner
- type Diagnostic
- type Divider
- func (d Divider) Between() (before, after ID)
- func (d Divider) Horizontal() bool
- func (d Divider) ID() ID
- func (d Divider) Index() int
- func (d Divider) MoveBy(delta int) bool
- func (d Divider) MoveTo(pos int) bool
- func (d Divider) Range() (lo, hi int)
- func (d Divider) Rect() Rect
- func (d Divider) Valid() bool
- type Docked
- type Edge
- type Extent
- type Float
- type FloatSize
- type Geometry
- func (g *Geometry) Apply() []Diagnostic
- func (g *Geometry) Area() Rect
- func (g *Geometry) Content(id ID) (Rect, bool)
- func (g *Geometry) Degraded() bool
- func (g *Geometry) Diagnostics() []Diagnostic
- func (g *Geometry) Divider(container ID, index int) (Divider, bool)
- func (g *Geometry) Dump() string
- func (g *Geometry) Has(id ID) bool
- func (g *Geometry) Hit(x, y int) Hit
- func (g *Geometry) HitAt(p Position) Hit
- func (g *Geometry) IDs() []ID
- func (g *Geometry) Owner(x, y int) ID
- func (g *Geometry) Rect(id ID) (Rect, bool)
- func (g *Geometry) Root() View
- func (g *Geometry) Shape() uint64
- func (g *Geometry) Size(id ID) (w, h int, ok bool)
- func (g *Geometry) TooSmall() (want Size, ok bool)
- func (g *Geometry) View(id ID) (View, bool)
- func (g *Geometry) Visible(id ID) bool
- type Gravity
- type Hit
- func (h Hit) Blocked() bool
- func (h Hit) Col() int
- func (h Hit) Content() Rect
- func (h Hit) Divider() (Divider, bool)
- func (h Hit) Empty() bool
- func (h Hit) Has(id ID) bool
- func (h Hit) ID() ID
- func (h Hit) InContent() bool
- func (h Hit) Local() Position
- func (h Hit) OnDivider() bool
- func (h Hit) Path() []ID
- func (h Hit) Point() Position
- func (h Hit) Rect() Rect
- func (h Hit) Row() int
- func (h Hit) View() (View, bool)
- type ID
- type Justify
- type Kind
- type Node
- func (n Node) Bind(s Sizer) Node
- func (n Node) Chrome(c Chrome) Node
- func (n Node) Collapse(c Collapse) Node
- func (n Node) CollapseBorders() Node
- func (n Node) Detached() Node
- func (n Node) Float(fs ...Float) Node
- func (n Node) Gap(cells int) Node
- func (n Node) Hidden(hidden bool) Node
- func (n Node) Hittable(hittable bool) Node
- func (n Node) ID() ID
- func (n Node) Justify(j Justify) Node
- func (n Node) Kind() Kind
- func (n Node) MaxSize(w, h int) Node
- func (n Node) MinScreen(w, h int) Node
- func (n Node) MinSize(w, h int) Node
- func (n Node) Pad(p Padding) Node
- func (n Node) Paint(p Painter) Node
- func (n Node) PaintString(f func(w, h int) string) Node
- func (n Node) Priority(p int) Node
- func (n Node) Replace(id ID, fn func(Node) Node) Node
- func (n Node) Resizable(s *Split) Node
- func (n Node) Tail(s string) Node
- func (n Node) Wrap(wrap bool) Node
- func (n Node) Z(z int) Node
- type Padding
- type PaintFunc
- type Painter
- type Position
- type Rect
- type RenderOption
- type Severity
- type Side
- type Size
- type Sizer
- type SizerFunc
- type Split
- type Surface
- func (s *Surface) Block(str string)
- func (s *Surface) BlockAt(r Rect, str string)
- func (s *Surface) Bounds() Rect
- func (s *Surface) CellAt(x, y int) *uv.Cell
- func (s *Surface) Drawable(d uv.Drawable, r Rect)
- func (s *Surface) Fill(c uv.Cell)
- func (s *Surface) FillRect(r Rect, c uv.Cell)
- func (s *Surface) SetCell(x, y int, c *uv.Cell)
- func (s *Surface) Size() (w, h int)
- func (s *Surface) String(x, y int, str string)
- func (s *Surface) Sub(r Rect) *Surface
- func (s *Surface) Tail() string
- func (s *Surface) WidthMethod() uv.WidthMethod
- func (s *Surface) WrapBlock(str string)
- type Title
- type View
- func (v View) Border() Padding
- func (v View) Children() []ID
- func (v View) Col(x int) int
- func (v View) Collapses() bool
- func (v View) Content() Rect
- func (v View) Depth() int
- func (v View) Dividers() []Rect
- func (v View) Hittable() bool
- func (v View) ID() ID
- func (v View) IsFloat() bool
- func (v View) Kind() Kind
- func (v View) Local(p Position) Position
- func (v View) Min() Size
- func (v View) Owns(x, y int) bool
- func (v View) Parent() (ID, bool)
- func (v View) Rect() Rect
- func (v View) Row(y int) int
- func (v View) Shared() []Rect
- func (v View) Size() Size
- func (v View) Titles() []Rect
- func (v View) Valid() bool
- func (v View) Visible() bool
- func (v View) Z() int
Examples ¶
Constants ¶
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 ¶
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 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 AnchorCorner ¶
AnchorCorner pins the float to a corner of its container.
func AnchorEdge ¶
AnchorEdge pins the float to an edge, aligned along it.
func AnchorPoint ¶
AnchorPoint puts a corner of the float on an absolute point — a context menu at the cell that was clicked.
type Background ¶
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 ¶
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.
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.
type Chrome ¶
type Chrome struct {
Border Border
Title Title // spliced into the top 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 ¶
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 ¶
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) Fits ¶
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 ¶
Inset is the total gap between a node's rectangle and its content: the border plus the padding inside it.
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 )
type Collapse ¶
type Collapse int
Collapse says what happens to a child when its container cannot fit every child's minimum size.
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 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 Diagnostic ¶
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) Horizontal ¶
Horizontal reports whether the divider moves along x — true in a Row, false in a Col.
func (Divider) Index ¶
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 ¶
MoveBy moves the divider by a number of cells, clamped as Divider.MoveTo.
func (Divider) MoveTo ¶
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 ¶
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.
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 ExtentFunc ¶
ExtentFunc builds an extent from a plain function of the available room.
func Fit ¶
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.
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 ¶
MustSolve is Solve for tests and examples: it panics instead of returning the programmer error.
func Solve ¶
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) Content ¶
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 ¶
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) Dump ¶
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) 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 ¶
HitAt is Geometry.Hit taking a position.
func (*Geometry) IDs ¶
IDs lists every node's ID in declaration order, root first. Anonymous nodes appear under their synthetic "#N" IDs.
func (*Geometry) Owner ¶
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 ¶
Rect returns a node's own rectangle, borders and all. ok is false when no node has that ID.
func (*Geometry) Root ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
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) Divider ¶
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) InContent ¶
InContent reports whether the point landed inside the content rather than on the node's border or padding.
func (Hit) Local ¶
Local is the position relative to the node's content rectangle. It is negative on the border.
func (Hit) OnDivider ¶
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 ¶
Path is the chain of nodes containing the point, root first. Use it to bubble an event up until something handles it.
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 )
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 Dock ¶
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 Stack ¶
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 ¶
Bind attaches a sizer, so the component inside this node is told the node's content size whenever Geometry.Apply runs.
func (Node) Chrome ¶
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 ¶
Collapse says what should happen to this node when its container runs out of room. The default is CollapseDrop.
func (Node) CollapseBorders ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Hittable controls whether hit tests can land on this node. Structural containers are usually left hittable; a decorative overlay is not.
func (Node) 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 ¶
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) MaxSize ¶
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 ¶
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 ¶
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 ¶
Pad insets the node's content rectangle. Children are laid out inside the padding; the node's own rectangle is unchanged.
func (Node) Paint ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Tail is appended to text the node has to cut short. The default is to cut with no marker.
type Padding ¶
type Padding struct{ Top, Right, Bottom, Left int }
Padding is an inset measured in cells, in CSS order.
func Pad ¶
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) Apply ¶
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) Horizontal ¶
Horizontal is the total inset along the x axis.
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 ¶
Position is a point in absolute screen coordinates. It is an alias for image.Point.
type Rect ¶
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.
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 )
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.
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 ¶
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 ¶
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) MarshalJSON ¶
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 ¶
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) UnmarshalJSON ¶
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.
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 ¶
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) Drawable ¶
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) Size ¶
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 ¶
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 ¶
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) WidthMethod ¶
func (s *Surface) WidthMethod() uv.WidthMethod
WidthMethod implements uv.Screen.
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 ¶
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) IsFloat ¶
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) Local ¶
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 ¶
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 ¶
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) Row ¶
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 ¶
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) Titles ¶
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.
Source Files
¶
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. |