Layout

OpenTUI uses Yoga to compute a renderable tree on a grid of terminal cells. It supports a defined set of Flexbox-like properties, not all browser CSS.

A horizontal size is a count of terminal columns. A vertical size is a count of terminal rows. These values are never character counts.

Spacing and growth#

import { BoxRenderable, RGBA, TextRenderable, createCliRenderer } from "@opentui/core"

const renderer = await createCliRenderer()
const foreground = RGBA.defaultForeground()
const fill = RGBA.fromIndex(238)

const row = new BoxRenderable(renderer, {
  width: 34,
  height: 5,
  border: true,
  borderColor: foreground,
  padding: 1,
  flexDirection: "row",
  gap: 2,
})

const fixed = new BoxRenderable(renderer, { width: 8, height: 1, backgroundColor: fill })
fixed.add(new TextRenderable(renderer, { content: "fixed 8", fg: foreground }))

const growing = new BoxRenderable(renderer, {
  flexGrow: 1,
  flexBasis: 0,
  height: 1,
  backgroundColor: fill,
})
growing.add(new TextRenderable(renderer, { content: "grow 20", fg: foreground }))

row.add(fixed)
row.add(growing)
renderer.root.add(row)

The shaded children occupy 8 and 20 columns. The border and padding use four columns. The gap uses two more.

The same layout properties work across the built-in renderable classes.

Supported options#

RenderableOptions supplies the shared renderable layout values. BoxOptions adds the three gap values.

Group Options Accepted values Default
Position position "relative" or "absolute" "relative"
Edges top, right, bottom, left number, "auto", or percentage unset
Dimensions width, height number, "auto", or percentage "auto"
Dimensions aspectRatio number (width in columns divided by height in rows) unset
Dimensions boxSizing "border-box" or "content-box" "border-box"
Limits minWidth, minHeight, maxWidth, maxHeight number or percentage unset
Margin margin, marginX, marginY, marginTop, marginRight, marginBottom, marginLeft number, "auto", or percentage 0
Padding padding, paddingX, paddingY, paddingTop, paddingRight, paddingBottom, paddingLeft number or percentage 0
Flex size flexGrow number 0
Flex size flexShrink number 0 for an initial numeric dimension, otherwise 1
Flex size flexBasis number, "auto", or percentage "auto"
Flow flexDirection "column", "column-reverse", "row", or "row-reverse" "column"
Flow flexWrap "no-wrap", "wrap", or "wrap-reverse" "no-wrap"
Flow layoutMode "flex" or "list", see List layout "flex"
Alignment alignItems Yoga align value "stretch"
Alignment alignContent Yoga align value "flex-start"
Alignment alignSelf Yoga align value "auto"
Alignment justifyContent start, end, center, or space distribution "flex-start"
Gaps on Box gap, rowGap, columnGap number or percentage 0
Clipping overflow "visible", "hidden", or "scroll" "visible"

Yoga align values are "auto", "flex-start", "center", "flex-end", "stretch", "baseline", "space-between", "space-around", and "space-evenly".

justifyContent accepts the same start, center, end, and three space-distribution values. It does not accept "auto", "stretch", or "baseline".

PositionTypeString also includes "static", but renderable option validation does not implement it. Use "relative" or "absolute".

The public TypeScript interface includes "auto" for min and max dimensions. The current runtime ignores that value for those four options.

A numeric value, translateX, and translateY must be finite and at most about 3.4e38 in magnitude, the 32-bit float range. Other values throw RangeError. Drawing clamps geometry to the signed 32-bit cell range, so a very large value moves a renderable off the screen instead of failing the frame. x, y, width, and height still report the unclamped layout.

Margin, padding, edge (top, right, bottom, left), and gap values beyond ±1e30 are stored as ±1e30, and a resolved percentage is limited the same way, so layout sums stay finite. getMargin(), getPadding(), and getGap() read back the stored value.

Alignment#

In a row, justifyContent distributes horizontal space and alignItems positions children vertically. A child can override the vertical alignment with alignSelf.

When children wrap onto multiple lines, alignContent distributes the lines along the cross axis. For example, alignContent: "space-between" leaves the extra height between the lines of a wrapped row.

const row = new BoxRenderable(renderer, {
  width: 32,
  height: 7,
  border: true,
  borderColor: foreground,
  paddingX: 1,
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
})

for (const [label, height] of [
  ["A", 1],
  ["B", 3],
  ["C", 1],
] as const) {
  const child = new BoxRenderable(renderer, {
    width: 6,
    height,
    alignSelf: label === "C" ? "flex-end" : "auto",
    backgroundColor: fill,
  })
  child.add(new TextRenderable(renderer, { content: label, fg: foreground }))
  row.add(child)
}
renderer.root.add(row)

A and B share a vertical center despite their different heights. C sits at the bottom.

Yoga alignment positions child boxes. It does not align characters inside a text renderable. Use textAlign for left, center, or right alignment of each rendered line inside the text width.

Automatic and intrinsic size#

An "auto" dimension lets Yoga derive size from children or from a renderable’s measure function. Text and editor renderables measure their content in native code.

Set aspectRatio to derive one dimension from the other. For example, a box with width: 12 and aspectRatio: 1.5 is 8 rows high when its height is otherwise unconstrained.

Yoga calls a measure function with exact, at-most, or unconstrained dimensions. Text measurement uses display-cell width and the active wrap mode.

wrapMode: "word" and "char" can increase measured height under a width constraint. wrapMode: "none" keeps the intrinsic line width.

textAlign does not change measured size. It is a draw offset inside the computed width.

A percentage dimension resolves against the parent’s corresponding size. If that parent lacks a definite size, the result can differ from a browser layout assumption.

Min and max dimensions constrain the result. Padding and borders consume space inside the computed box.

boxSizing: "content-box" adds padding and borders to the width, height, and their limits instead. A box with width: 10, height: 3, a border, and padding: 1 is then 14 columns by 7 rows, and its content gets 10 by 3. The default is "border-box", unlike CSS’s initial value. On a ScrollBox, "content-box" also adds the scrollbar gutters, which are the box’s own padding, to its size.

Relative and absolute flow#

Relative children take part in flex layout. Their edge values offset the Yoga position.

Absolute children do not consume space in normal flex flow. Their edges position them against the containing layout box.

Absolute text also uses its intrinsic measure without the relative child’s at-most clamp. Set a width when you need predictable wrapping.

Use absolute positioning for overlays and fixed geometry. Use flex flow for ordinary page structure.

List layout#

layoutMode: "list" lays out a long column of rows, such as a log or a transcript, without a flex pass over every row. When one row changes, or a row is appended at the end, the other rows are not laid out again. Set it on ScrollBox content with contentOptions: { layoutMode: "list" }.

Apart from the rules below, a list lays out like a flex column with overflow: "scroll". So the list’s height does not cap its rows, and a percent height inside an auto-height row resolves against no height.

Property In a list
The list’s flexDirection and flexWrap Rows always stack top to bottom in one column
The list’s justifyContent, rows’ marginTop: "auto" and marginBottom: "auto" Rows start at the top; auto top and bottom margins count as 0
Rows’ flexGrow, flexShrink, and flexBasis Ignored: each row keeps its own height
Percent height, minHeight, maxHeight, top, and bottom of rows Resolve against no height
A percent gap 0 unless the list has a definite height

Widths, alignItems, alignSelf, margins, padding, borders, point gaps, aspectRatio, relative insets, and display: "none" work as in a column. Absolute children are placed as in flex layout, and they still follow the list’s flexDirection, justifyContent, and alignItems. layoutMode has no effect on a renderable that measures its own content, such as text.

Cell rounding#

Yoga uses a point scale factor of 1. It rounds computed edges to whole terminal cells while preserving the layout total.

Percentage and flex calculations can produce fractions before this step. Adjacent children can therefore receive different rounded widths.

These three children use the same grow factor and zero basis:

const child = new BoxRenderable(renderer, {
  flexGrow: 1,
  flexBasis: 0,
  minWidth: 0,
})

A 32-column bordered row leaves 30 inner columns. Adding one column gives the middle child an extra cell, without gaps or overlaps:

Renderable getters expose computed integer geometry after a layout pass. OpenTUI clamps exposed width and height to at least one cell.

Paint does not clamp. A node that Yoga sizes to zero width or height draws no cells and receives no mouse events, although its getters report one cell. Its children still paint unless the node clips them. For example, when a column is too short for its children, flexShrink can reduce a text to zero rows, and that text disappears. Give the text flexShrink: 0 to keep it visible.

Read style and geometry#

x, y, width, height, and getLayout() report computed geometry from the last layout pass.

To read the style that was set, call the method with the name of the matching Yoga Node getter. It returns the same Value or enum type. A change is visible at once, before the next layout pass:

box.maxWidth = 40
box.getMaxWidth() // { unit: Unit.Point, value: 40 }
box.width // the computed width from the last layout pass
Options Getters
width, height getWidth(), getHeight()
minWidth, minHeight, maxWidth, maxHeight getMinWidth(), getMinHeight(), getMaxWidth(), getMaxHeight()
Margin and padding options getMargin(edge), getPadding(edge)
gap, rowGap, columnGap getGap(gutter)
flexGrow, flexShrink, flexBasis getFlexGrow(), getFlexShrink(), getFlexBasis()
flexDirection, flexWrap getFlexDirection(), getFlexWrap()
alignItems, alignSelf, justifyContent getAlignItems(), getAlignSelf(), getJustifyContent()
alignContent, aspectRatio getAlignContent(), getAspectRatio()
boxSizing getBoxSizing()
position getPositionType()

An edge or gutter getter reads only the value set for that edge or gutter. padding sets Edge.All, paddingX sets Edge.Horizontal, paddingY sets Edge.Vertical, and paddingLeft sets Edge.Left. The margin and gap options work the same way. After padding: 2, getPadding(Edge.Left) returns a Unit.Undefined value, but layout still pads the left side by 2, because Yoga falls back from Edge.Left to Edge.Horizontal and then to Edge.All. Renderables have no getter for computed padding, margin, or border.

top, right, bottom, left, and overflow have property getters. Assign an option to change its style.

Assigning null or undefined to a layout option restores the default in Supported options. A class that sizes itself, such as InputRenderable or TabSelectRenderable, restores its own width or height. Other class defaults, such as the row direction of ScrollBoxRenderable, are not restored, and flexShrink becomes 1. A margin, padding, or gap edge becomes unset, so layout falls back to its shorthand again. Assigning 0 sets the edge instead:

const box = new BoxRenderable(renderer, { paddingX: 2 })
box.getPadding(Edge.Left) // { unit: Unit.Undefined, value: NaN }
box.paddingLeft = 5 // pads the left side by 5
box.paddingLeft = undefined // pads it by 2 again, from paddingX

To write back a Value that a getter returned, assign undefined for Unit.Undefined, "auto" for Unit.Auto, `${value}%` for Unit.Percent, and value for Unit.Point. Assigning a number to width or height also changes a flexShrink of 1 to 0, so restore getFlexShrink() with them.

Resize behavior#

A terminal resize keeps the same renderable instances. The renderer resizes its root and runs Yoga again with the new column and row counts.

With flexWrap: "wrap", whole children move to the next row when they no longer fit. The container’s automatic height grows to include them:

const row = new BoxRenderable(renderer, {
  width: "100%",
  border: true,
  borderColor: foreground,
  paddingX: 1,
  flexDirection: "row",
  flexWrap: "wrap",
  alignItems: "flex-start",
  columnGap: 2,
  rowGap: 1,
})

for (const content of ["A", "B", "C"]) {
  const child = new BoxRenderable(renderer, {
    width: 8,
    height: 1,
    flexShrink: 0,
    backgroundColor: fill,
  })
  child.add(new TextRenderable(renderer, { content, fg: foreground }))
  row.add(child)
}
renderer.root.add(row)

The same children before and after narrowing the terminal:

Computed x, y, width, and height can all change. When a visible renderable’s size changes, OpenTUI first resizes its frame buffer if it is buffered. Then it calls onResize(width, height).

FrameBufferRenderable resizes its public frameBuffer in its onResize() override, then calls the base hook.

The base onResize() calls onSizeChange and emits the renderable’s "resize" event. After onResize() returns, OpenTUI requests another render.

Renderer resize listeners receive the render-region width and height.

Custom streams must call renderer.resize(columns, rows). Local process.stdout sessions use SIGWINCH automatically.

Common failures#

  • A numeric initial width or height sets the default flexShrink to 0. Set flexShrink when the node must contract.
  • An absolute child does not increase its parent’s automatic size.
  • A percentage needs a useful parent size.
  • overflow: "scroll" clips like a Yoga overflow mode, but it does not add scroll state. Use ScrollBox.
  • Gap options belong to Box, not every renderable class.
  • visible = false removes a renderable from layout.
  • A scene holds at most 256 levels, counting the root. An add() or insertBefore() that nests deeper throws NativeError with status ObjectLimit.
  • Text can contain fewer graphemes than cells or more UTF-16 units than cells. See Text and terminal cells.

Next#

Read Renderables for tree mutation. Use the advanced Yoga API only when the shared options do not cover your case.

Changes0.9.8, 0.9.0, 0.8.3
0.9.8
core: The boxSizing layout option accepts "content-box", which adds padding and borders to the size and its limits. getBoxSizing() returns the value, and React and Solid props also accept it. (#2183)
core: flexBasis accepts a percentage, such as "50%". Before, Core discarded a percentage value without an error. (#2183)
native: A percentage flexBasis or percentage padding now updates when its parent resizes, unless the parent takes its size from its content. Before, a 50% child of a row that grew from 20 to 30 cells stayed at 10 cells. (#2192)
Changed parseBoxSizing.
0.9.0
core: The alignContent and aspectRatio layout options work on renderables, ScrollBox content, and React and Solid props. getAlignContent() and getAspectRatio() read them. Requested by @nwidynski. (#2096)
core: layoutMode: "list" lays out children as a column without a flex pass over each row, so a change to one row lays out only that row. ScrollBox content takes it through contentOptions. (#1989, #1960, #1987)
core: Layout after a change now matches a fresh layout. This fixes text widened by minWidth, children one cell off in a cached box, a column in a baseline-aligned row, stale wraps after small width changes, and nodes added under display: none, which now read 0 × 0. (#1947, #1968, #1995, #2009)
Added parseAlignContent, parseLayoutMode, LayoutModeString.
0.8.3
core: Layout no longer makes items millions of cells wide when every item of an overflowing flex line freezes at its minimum size. The vendored Yoga includes the upstream fix. (#1922)
core: Text measurement treats a width that is less than 0.0001 below a whole cell as that cell. After a resize, flex-shrink and flex-grow layouts no longer keep a text one cell wider than a fresh layout. (#1926)