Skip to content

Common patterns

Copy a complete recipe to build a status display, table, or dashboard. Each example includes its inputs and renders the output shown below. After installing the dependencies, save a recipe as example.ts and run bun run example.ts with Bun or npx tsx example.ts with Node.

Compose transformations

Functions such as moveRight support both data-first and data-last calls. Constructors such as text take their own inputs. Use pipe or a box's .pipe() method to compose transformations. Box.border<never> adds an unannotated border while retaining the content annotations.

╭──────────╮
│     Hello│
╰──────────╯
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { pipe } from "effect";
 
const box1 = pipe(
  Box.text("Hello"),
  Box.moveRight(5),
  Box.annotate(Ansi.bold),
  Box.border<never>("rounded")
);
const box2 = Box.moveRight(Box.text("Hello"), 5).pipe(
  Box.annotate(Ansi.bold),
  Box.border<never>("rounded")
);
const box3 = Box.text("Hello").pipe(
  Box.moveRight(5),
  Box.annotate(Ansi.bold),
  Box.border<never>("rounded")
);
const output = Box.renderPrettySync(box1);
console.log(output);

Compare boxes

Boxes implement Effect's Equal and Hash interfaces, so you can use boxes in HashMap and HashSet. Equality compares box structure and annotations. Matching rendered text alone does not establish equality.

Same text boxes: true
Different text: false
Added annotation: false
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { pipe, Equal } from "effect";
 
const a = Box.text("hello");
const b = Box.text("hello");
const c = Box.text("world");
const styled = a.pipe(Box.annotate(Ansi.bold));
const output = Box.renderPrettySync(
  Box.text(
    [
      `Same text boxes: ${Equal.equals(a, b)}`,
      `Different text: ${Equal.equals(a, c)}`,
      `Added annotation: ${Equal.equals(a, styled)}`,
    ].join("\n")
  )
);
console.log(output);

Show status indicators

Return a box from a helper, then combine the boxes vertically. The icon and text share one annotation.

✓ Tests passed
✗ Build failed
⚠ 3 warnings
ℹ Running...
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { pipe } from "effect";
 
const statusIcon = (
  icon: string,
  text: string,
  color: Ansi.AnsiAnnotation
): Box.Box<Ansi.AnsiStyle> =>
  Box.text(`${icon} ${text}`).pipe(Box.annotate(color));
 
const statuses = Box.vcat(
  [
    statusIcon("✓", "Tests passed", Ansi.green),
    statusIcon("✗", "Build failed", Ansi.red),
    statusIcon("⚠", "3 warnings", Ansi.yellow),
    statusIcon("ℹ", "Running...", Ansi.blue),
  ],
  Box.left
);
const output = Box.renderPrettySync(statuses);
console.log(output);

Draw a progress bar

Clamp progress to the range from zero to the total. A nonpositive total displays zero percent. Reject nonfinite inputs and widths that are not nonnegative integers before calling repeat. The width counts bar cells; the percentage and border add columns.

╭──────────────────────────────────────────────────────╮
│███████████████████████████████████░░░░░░░░░░░░░░░ 70%│
╰──────────────────────────────────────────────────────╯
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { pipe } from "effect";
 
const progressBar = (
  progress: number,
  total: number,
  width: number
): Box.Box<Ansi.AnsiStyle> => {
  if (!Number.isFinite(progress) || !Number.isFinite(total)) {
    throw new RangeError("Progress and total must be finite");
  }
  if (!Number.isInteger(width) || width < 0) {
    throw new RangeError("Width must be a nonnegative integer");
  }
  const ratio = total > 0 ? Math.max(0, Math.min(progress / total, 1)) : 0;
  const filled = Math.round(ratio * width);
  return Box.hcat(
    [
      Box.text("█".repeat(filled)).pipe(Box.annotate(Ansi.green)),
      Box.text("░".repeat(width - filled)).pipe(Box.annotate(Ansi.dim)),
      Box.text(` ${Math.round(ratio * 100)}%`),
    ],
    Box.top
  );
};
const bar = progressBar(70, 100, 50).pipe(Box.border<never>("rounded"));
const output = Box.renderPrettySync(bar);
console.log(output);

Build a data table

Give every row one cell per header. This recipe uses fixed-width columns and truncates cells that exceed that width. Apply the outer border in the sample call.

╭──────────────────────────────────────────────────╮
│Name            │Role            │Status          │
│──────────────────────────────────────────────────│
│Alice           │Engineer        │Active          │
│Bob             │Designer        │Away            │
│Carol           │Manager         │Offline         │
╰──────────────────────────────────────────────────╯
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { pipe } from "effect";
 
const table = (
  headers: readonly string[],
  rows: readonly (readonly Box.Box<Ansi.AnsiStyle>[])[]
): Box.Box<Ansi.AnsiStyle> => {
  const colWidth = 16;
  if (
    headers.length === 0 ||
    rows.some((row) => row.length !== headers.length)
  ) {
    throw new RangeError(
      "Provide headers and one cell per header in every row"
    );
  }
  const headerRow = Box.punctuateH(
    headers.map((header) =>
      Box.text(header).pipe(
        Box.annotate(Ansi.bold),
        Box.alignHoriz(Box.left, colWidth)
      )
    ),
    Box.top,
    Box.text("│")
  );
  const separator = Box.text(
    "─".repeat(headers.length * colWidth + headers.length - 1)
  );
  const dataRows = rows.map((row) =>
    Box.punctuateH(
      row.map((cell) => cell.pipe(Box.alignHoriz(Box.left, colWidth))),
      Box.top,
      Box.text("│")
    )
  );
  return Box.vcat([headerRow, separator, ...dataRows], Box.left);
};
const people = table(
  ["Name", "Role", "Status"],
  [
    [
      Box.text("Alice"),
      Box.text("Engineer"),
      Box.text("Active").pipe(Box.annotate(Ansi.green)),
    ],
    [
      Box.text("Bob"),
      Box.text("Designer"),
      Box.text("Away").pipe(Box.annotate(Ansi.yellow)),
    ],
    [
      Box.text("Carol"),
      Box.text("Manager"),
      Box.text("Offline").pipe(Box.annotate(Ansi.dim)),
    ],
  ]
).pipe(Box.border<never>("rounded"));
const output = Box.renderPrettySync(people);
console.log(output);

Align keys and values

A spacer uses the remaining width between the label and value. Choose a width that fits both fixed boxes and padding. This panel is 40 columns before its outer border, which adds two columns.

╭────────────────────────────────────────╮
│                                        │
│ Host:                          prod-01 │
│ Status:                        healthy │
│ Uptime:                         14d 3h │
│ Load:                             0.42 │
│                                        │
╰────────────────────────────────────────╯
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { Flex, Container } from "effect-boxes/Layout";
import { pipe } from "effect";
 
const kvPanel = (
  entries: readonly (readonly [string, Box.Box<Ansi.AnsiStyle>])[],
  width: number
): Box.Box<Ansi.AnsiStyle> =>
  Container.make({ width, padding: 1 }, (ctx) =>
    Box.vcat(
      entries.map(([key, value]) =>
        Flex.row(
          [
            Flex.fixed(Box.text(`${key}:`).pipe(Box.annotate(Ansi.dim))),
            Flex.spacer(),
            Flex.fixed(value),
          ],
          ctx.innerWidth
        )
      ),
      Box.left
    )
  ).pipe(Box.border<never>("rounded"));
const panel = kvPanel(
  [
    ["Host", Box.text("prod-01")],
    ["Status", Box.text("healthy").pipe(Box.annotate(Ansi.green))],
    ["Uptime", Box.text("14d 3h")],
    ["Load", Box.text("0.42")],
  ],
  40
);
const output = Box.renderPrettySync(panel);
console.log(output);

Reuse component styles

Keep helpers pure by returning boxes. This section combines a heading, a separator, and a bordered badge.

Deployment
────────────────────────────────────────
╭─────────╮
│ healthy │
╰─────────╯
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { pipe } from "effect";
 
const heading = (text: string): Box.Box<Ansi.AnsiStyle> =>
  Box.text(text).pipe(Box.annotate(Ansi.combine(Ansi.bold, Ansi.white)));
const badge = (
  text: string,
  color: Ansi.AnsiAnnotation
): Box.Box<Ansi.AnsiStyle> =>
  Box.text(` ${text} `).pipe(Box.annotate(color), Box.border<never>("rounded"));
const section = (
  title: string,
  content: Box.Box<Ansi.AnsiStyle>
): Box.Box<Ansi.AnsiStyle> =>
  Box.vcat([heading(title), Box.text("─".repeat(40)), content], Box.left);
const output = Box.renderPrettySync(
  section("Deployment", badge("healthy", Ansi.green))
);
console.log(output);

Compose Container, Flex, and Grid

Set both width and height when a child uses ctx.innerHeight. Without a height, innerHeight is zero. This dashboard reserves 12 rows including padding, then gives the remaining inner rows to the activity panel.


 Dashboard                                                  v1.0
 Requests             Errors               Latency
 1,204                0                    24 ms
 Recent activity
 Deployment completed
 All checks passed




import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { Flex, Container, Grid } from "effect-boxes/Layout";
import { pipe } from "effect";
 
const heading = (text: string): Box.Box<Ansi.AnsiStyle> =>
  Box.text(text).pipe(Box.annotate(Ansi.bold));
const label = (text: string): Box.Box<Ansi.AnsiStyle> =>
  Box.text(text).pipe(Box.annotate(Ansi.dim));
const kpiData = [
  { name: "Requests", value: "1,204" },
  { name: "Errors", value: "0" },
  { name: "Latency", value: "24 ms" },
];
const renderKpiCard = (kpi: {
  readonly name: string;
  readonly value: string;
}): Box.Box<Ansi.AnsiStyle> =>
  Box.vcat([label(kpi.name), heading(kpi.value)], Box.left);
const mainContent = Box.text(
  "Recent activity\nDeployment completed\nAll checks passed"
);
const dashboard = Container.make(
  { width: 65, height: 12, padding: 1 },
  (ctx) => {
    const header = Flex.row(
      [
        Flex.fixed(heading("Dashboard")),
        Flex.spacer(),
        Flex.fixed(label("v1.0")),
      ],
      ctx.innerWidth
    );
    const kpis = Grid.auto(kpiData.map(renderKpiCard), ctx.innerWidth, {
      minColWidth: 20,
    });
    return Flex.col(
      [Flex.fixed(header), Flex.fixed(kpis), Flex.grow(mainContent)],
      ctx.innerHeight
    );
  }
);
const output = Box.renderPrettySync(dashboard);
console.log(output);

Choose a style from status data

Use Match to handle every supported status. The Status union restricts this helper to known values. Decode external input before passing it to the helper.

Database                              ok
Cache                               warn
Queue                              error
import * as Box from "effect-boxes/Box";
import * as Ansi from "effect-boxes/Ansi";
import { Flex } from "effect-boxes/Layout";
import { pipe, Match } from "effect";
 
type Status = "ok" | "warn" | "error";
const statusColor = (status: Status): Ansi.AnsiAnnotation =>
  Match.value(status).pipe(
    Match.when("ok", () => Ansi.green),
    Match.when("warn", () => Ansi.yellow),
    Match.when("error", () => Ansi.red),
    Match.exhaustive
  );
const renderStatus = (name: string, status: Status): Box.Box<Ansi.AnsiStyle> =>
  Flex.row(
    [
      Flex.fixed(Box.text(name)),
      Flex.spacer(),
      Flex.fixed(Box.text(status).pipe(Box.annotate(statusColor(status)))),
    ],
    40
  );
const output = Box.renderPrettySync(
  Box.vcat(
    [
      renderStatus("Database", "ok"),
      renderStatus("Cache", "warn"),
      renderStatus("Queue", "error"),
    ],
    Box.left
  )
);
console.log(output);