Skip to content

Architecture

A Box stores text, dimensions, and annotations. Composition builds a tree; a renderer turns that tree into output. Keeping these steps separate lets you reuse a layout with different renderers.

This page explains the internal model. For the public rendering helpers, start with Rendering.

The box tree

A Box<A> has rows, cols, an optional Annotation<A>, and a content field. The public Box.Content<A> union describes five node types:

NodeStored contentRole
BlankNo textReserve empty cells
TextA stringStore a line of text
RowChild boxesJoin children horizontally
ColChild boxesJoin children vertically
SubBoxA child and two alignmentsFit the child within the parent's dimensions

hcat and vcat compute the combined dimensions when you compose the layout. They also align their children, which can add SubBox wrappers. Rendering visits these nodes later. Some transformations, such as cropping, traverse the existing tree during construction too.

The following example prints both a layout and its actual tree. Each node label shows its height and width. The empty cell above A comes from its vertical alignment beside the two-line box.

 B
AC

Row (rows=2, cols=2)
  SubBox (rows=2, cols=1)
    Col (rows=1, cols=1)
      SubBox (rows=1, cols=1)
        Text (rows=1, cols=1)
  SubBox (rows=2, cols=1)
    Col (rows=2, cols=1)
      SubBox (rows=1, cols=1)
        Text (rows=1, cols=1)
      SubBox (rows=1, cols=1)
        Text (rows=1, cols=1)
import * as Box from "effect-boxes/Box";
 
const layout = Box.hcat([Box.text("A"), Box.text("B\nC")], Box.bottom);
const describe = (self: Box.Box<unknown>, indent = ""): string => {
  const label = `${indent}${self.content._tag} (rows=${self.rows}, cols=${self.cols})`;
  switch (self.content._tag) {
    case "Row":
    case "Col":
      return [
        label,
        ...self.content.boxes.map((child) => describe(child, `${indent}  `)),
      ].join("\n");
    case "SubBox":
      return `${label}\n${describe(self.content.box, `${indent}  `)}`;
    default:
      return label;
  }
};
const output = `${Box.renderPlainSync(layout)}\n\n${describe(layout)}`;
console.log(output);

Width in terminal cells

JavaScript string length counts UTF-16 code units. Box dimensions count terminal cells. The internal width calculation strips recognized ANSI escape sequences, segments text into graphemes, and measures those segments.

ASCII letters occupy one cell. Wide CJK characters and recognized emoji sequences occupy two. A combining mark attached to a letter does not add another cell. The example reports the library's measurements; terminal fonts and emoji support can affect how a terminal displays those characters.

╭──────────────────────────╮
│A: JS length=1, cells=1   │
│你好: JS length=2, cells=4│
│👩‍💻: JS length=5, cells=2  │
│é: JS length=2, cells=1   │
╰──────────────────────────╯
import * as Box from "effect-boxes/Box";
 
const samples = ["A", "你好", "👩‍💻", "e\u0301"];
const measurements = samples.map((text) =>
  Box.text(`${text}: JS length=${text.length}, cells=${Box.text(text).cols}`)
);
const layout = Box.vcat(measurements, Box.left).pipe(Box.border("rounded"));
const output = Box.renderPlainSync(layout);
console.log(output);

Width measurements determine padding, alignment, and cropping. A wide glyph that is partly clipped becomes spaces in the surviving cells, rather than half a glyph. Using Layout shows clipping examples.

Annotations belong to nodes

An annotation attaches data without changing the box's dimensions. Composing boxes keeps their child annotations in the tree. Box.annotate replaces the annotation on its target node; it does not combine that annotation with a new one. To retain a child's style while annotating a parent, compose a wrapper first.

The type parameter records possible annotation data, such as ANSI styles, HTML annotations, or reactive IDs. Box<never> has no annotation data. A union such as Box<AnsiStyle | Reactive> describes a tree that can contain either kind of data, not two annotations stored on one node.

Each renderer decides which annotations it understands. The ANSI renderer interprets styles; the plain renderer discards them. The two outputs below come from the same styled layout.

ANSI:  Ready
Plain: Ready
import { Effect } from "effect";
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import * as Renderer from "effect-boxes/Renderer";
 
const layout = Box.text("Ready").pipe(
  Box.annotate(Ansi.combine(Ansi.green, Ansi.bold))
);
const render = Renderer.render(layout);
const terminal = Effect.runSync(
  render.pipe(Effect.provide(Renderer.AnsiRendererLive))
);
const plain = Effect.runSync(
  render.pipe(Effect.provide(Renderer.PlainRendererLive))
);
const output = `ANSI:  ${terminal}\nPlain: ${plain}`;
console.log(output);

Using Annotation covers replacement, nesting, and application metadata. Using Html explains HTML serialization.

Tree rendering and frame rendering

The library has two rendering paths. Choose the tree renderer for ordinary Box composition, HTML annotations, or terminal command serialization. Choose frames for overlapping layers and queries about visible reactive regions.

PathStepsRequired service
Renderer.render(box)Visit nodes, fit lines, interpret annotations, join linesRenderer
Renderer.frame(boxOrStack)Resolve geometry and visibility, encode paint runs, join linesFrameEncoder

The tree-oriented Renderer service uses Effect's Context.Service. Its renderContent visits children and combines their lines. A TextProcessor fits text to node dimensions, and postProcess interprets each node's annotation. Providing a renderer layer selects this behavior.

Frame rendering separates geometry from encoding. Renderer.resolve requires no renderer service and produces an immutable snapshot with reactive regions. Renderer.encode sends the snapshot's paint runs to a FrameEncoder. The encoder receives text and effective styles at resolved positions; it does not decide which layer is visible.

This example resolves once, then encodes the same snapshot as ANSI and plain text:

ANSI frame
╭─────╮
│Ready│
╰─────╯

Plain frame
╭─────╮
│Ready│
╰─────╯
import { Effect } from "effect";
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import * as Renderer from "effect-boxes/Renderer";
import * as FrameEncoder from "effect-boxes/FrameEncoder";
 
const layout = Box.text("Ready").pipe(
  Box.annotate(Ansi.green),
  Box.border("rounded")
);
const resolved = Effect.runSync(Renderer.resolve(layout));
const terminal = Effect.runSync(
  Renderer.encode(resolved).pipe(
    Effect.provide(FrameEncoder.AnsiFrameEncoderLive)
  )
);
const plain = Effect.runSync(
  Renderer.encode(resolved).pipe(
    Effect.provide(FrameEncoder.PlainFrameEncoderLive)
  )
);
const output = `ANSI frame\n${terminal.output}\n\nPlain frame\n${plain.output}`;
console.log(output);

Keep the original resolved object for encoding and hit testing. Copying its public fields loses the private data associated with the snapshot. Frame resolution supports ANSI styles and reactive IDs. Commands and arbitrary annotation data fail with FrameResolutionError; encoding failures use FrameEncodingError.

The built-in plain and ANSI renderer layers also provide their corresponding frame encoders. A custom tree renderer needs a separate FrameEncoder layer to support frames. The HTML renderer has no frame encoder.

Render overlapping boxes shows layer ordering, clipping, and region queries. Using Reactive distinguishes layout coordinates from absolute terminal coordinates.

Why keep composition separate from output?

A tree preserves child structure and metadata until rendering. The same layout can produce styled terminal output or plain text without changing its content. Composition is pure, so constructing a layout does not write to a terminal.

Annotations keep renderer-specific data beside the content it describes. Renderers can interpret that data differently. HTML serialization produces markup, while ANSI serialization produces text and escape sequences; browser layout still follows HTML and CSS rules rather than terminal-cell geometry.

Effect layers make renderer selection an explicit dependency. A caller can choose plain output for redirected logs and ANSI output for an interactive terminal. The renderer does not automatically detect stdout capabilities.

Renderer API and FrameEncoder API describe the two service contracts.