tinsel 1.1.0

Clean terminal output with a little sparkle: live step lists, spinners, tables, trees, prompts and full-screen apps.
Documentation

tinsel

crates.io docs.rs License MSRV

Clean terminal output for Rust CLIs, with a little sparkle. Live step lists, spinners, tables, trees, prompts and error reports that all look like they belong together.

use tinsel::prelude::*;

let live = Live::new("deploy", "my-app → production");
let build = live.step("Build");
let upload = live.step("Upload");

build.start();
build.done();
upload.start();
upload.progress(0.5, "6 / 12 MB");
upload.done();

live.finish_with_card(Card::success("deployed").kv("url", "https://my-app.example.com"));
  deploy  my-app → production

    ●    Build                                                        1.2s
    ●    Upload                                                       1.7s

  ╭────────────────────────────────────────────────────────────────────────╮
  │  ● deployed in 3.8s                                                    │
  │                                                                        │
  │  url       https://my-app.example.com                                  │
  ╰────────────────────────────────────────────────────────────────────────╯

Why tinsel?

Most CLIs bolt together a spinner crate, a table crate, a prompt crate and a colour crate, and end up looking like four different programs. tinsel is one small library with one visual language: pink accents, quiet greys, eased animation, and a twinkle when something finishes.

  • It learns: steps remember how long they took, so next run a spinner becomes a real estimate: usually 42s · 18s left
  • It knows if you're watching: switch windows during a long run and you get a desktop notification when it ends; come back and whatever finished meanwhile twinkles
  • It fits your terminal: detects light and dark backgrounds and redraws the palette to suit, or in another accent colour for your brand
  • It speaks JSON too: one switch turns every step, message and error into JSON lines for tools, or quiets everything but problems
  • Zero dependencies: nothing in your lockfile but tinsel
  • One shape for everything: one-liners print; anything bigger is a Block you can print, format, or test
  • Builders that read like the output: Card::success("deployed").kv("url", …)
  • Errors you can match on: prompts return prompt::Error::Cancelled, not a mystery io::Error
  • Behaves in CI: no colour or animation when piped, NO_COLOR respected, plain [ok] Build (1.2s) lines in logs
  • Panics stay tidy: a panic mid-run leaves the last frame on screen and prints a proper report, not a scrambled terminal
  • Testable: set_color_mode(ColorMode::None) and .plain() give you exact text to assert on, and Live::headless runs a display on a clock you control

Install

cargo add tinsel

Quickstart

One task with a spinner, then a message:

let files = tinsel::spin("Counting files", || count_files());
tinsel::success(&format!("found {files} files"));

A step list for anything with stages: see the example at the top. Steps can run at the same time from different threads, have sub-steps, and log lines above the display:

let build = live.step("Build");
let targets = [build.step("linux"), build.step("macos")];   // drawn indented, folded once they pass
build.start();
std::thread::scope(|s| {
    for t in &targets {
        s.spawn(move || { t.start(); compile(t); t.done(); });
    }
});
build.done();
live.log("signed with Developer ID");                          // printed above, kept on screen

Steps that don't run can say why: lint.skip("nothing changed"), upload.cancel("stopped by hand"), or release.wait("waiting for approval") until someone says go, then release.start(). A failed step can start() again, and its timer starts over.

Progress bars can be a thin line (the default) or a waveform that lights up as it plays through, like an audio track: Live::new(…).bar(BarStyle::Waveform).

Run real commands as steps. The latest line of output shows as the step's detail; if it fails, its last lines stay under it:

use std::process::Command;

build.run(Command::new("cargo").args(["build", "--release"]))?;
push.command(Command::new("docker").args(["push", "my-app"]))
    .timeout(Duration::from_secs(120))
    .retries(2)
    .run()?;
fetch.retry(3, || download(url))?;      // any closure returning a Result

See where the time went, with live.finish_with_timeline():

  Build      ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                  1.7s
    linux    ━━━━━━━━━━━━━━━━━━━━━━━                           1.2s
    macos    ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                  1.7s
  Publish                                    ━━━━━━━━━━━━━     0.7s
             ──────────────────────────────────────────────
             0s                                          2.9s

Anything else, redrawn in place: a Region calls your closure a few times a second and draws the Block it returns, a table of services say, with lines logged above it. It's cleared when it finishes, unless you keep() the last frame:

let region = tinsel::Region::new(move || status_table(&state.lock().unwrap())).keep();
region.log("api is up");
region.finish();

A loop with a progress bar:

use tinsel::ProgressIterator;

for file in files.iter().progress("Indexing") {
    index(file);
}

Ask questions, and handle someone pressing Ctrl-C. Long lists filter as you type:

use tinsel::prompt;

match prompt::select("Deploy to", &["staging", "production"]) {
    Ok(i) => deploy(i),
    Err(prompt::Error::Cancelled) => std::process::exit(130),
    Err(e) => tinsel::Report::from_error("couldn't ask", &e).eprint(),
}

Text questions can validate, and ask again until the answer passes:

let port = prompt::Input::new("Port")
    .placeholder("8080")
    .validate(|s| s.parse::<u16>().map(|_| ()).map_err(|_| "a port is 1-65535".into()))
    .ask()?;
let replicas: u32 = prompt::number("Replicas", Some(3))?;
let live_on = prompt::date("Go live on", None)?;                  // a calendar
let notes = prompt::editor("Release notes", "## What's new\n")?;   // opens $EDITOR
let region = prompt::Input::new("Region").suggestions(regions).ask()?;  // Tab completes
let path = prompt::Input::new("Config").paths().ask()?;                  // like a shell
prompt::confirm_typing("Delete my-app?", "my-app")?;                       // type it to go on

Several questions can be asked as one Form: ← goes back to change an answer, and at the end they're all shown, to change any of them before going on:

use tinsel::prompt::{Confirm, Form, Input, Select};

let answers = Form::new()
    .question("name", Input::new("Project name").default("my-app"))
    .question("target", Select::new("Deploy to").options(["staging", "production"]))
    .question("tag", Confirm::new("Tag the release?").default(true))
    .ask()?;
deploy(answers.text("name"), answers.choice("target"), answers.yes("tag"));

Lists can be grouped, and say why an option can't be picked:

let service = prompt::Select::new("Service")
    .heading("Frontend").option("web").disabled("docs", "deploys paused")
    .heading("Backend").options(["api", "worker"])
    .back()                                       // ← returns prompt::Error::Back
    .ask()?;
let version = prompt::Dropdown::new("Roll back to")
    .option("v1.2.0").note("3 days ago").badge("latest")
    .option("v1.1.0").note("2 weeks ago")
    .allow_custom()                               // or type a version that isn't listed
    .ask()?;

Help that looks like the rest of your CLI, with a short entrance on a terminal: lines fade in one after another while the name shimmers:

tinsel::Help::new("deploy", "ship an app to the cloud")
    .version(env!("CARGO_PKG_VERSION"))
    .usage("deploy [OPTIONS] <APP>")
    .command("status", "what's running where")
    .flag("--region <NAME>", "where to deploy")
    .example("deploy my-app --region us-east-1", "ship to the US east region")
    .animate();

Read the command line from one description, which draws --help too. A mistake is a report that says what was probably meant:

let cli = tinsel::Cli::new("deploy", "ship an app to the cloud")
    .version(env!("CARGO_PKG_VERSION"))
    .flag("-r, --region <NAME>", "where to deploy")
    .flag("-q, --quiet", "only print problems")
    .arg("<APP>", "what to ship")
    .command(tinsel::Cli::new("status", "what's running where"));
let args = cli.parse();               // --help, --version and mistakes print and exit

let region = args.value("region").unwrap_or("eu-west-2");
let replicas: u32 = args.value_as("replicas").unwrap_or(1);
  ✕  there's no --regon flag
  →  did you mean --region?

It does what most programs need (flags, options, arguments, one level of subcommands, values parsed into types) and no more; for rules between flags or anything fancier, clap is the one to reach for.

Documents: tinsel::markdown(changelog).page() draws Markdown (headings, lists, tables, code coloured by language) and pages it if it's long; tinsel::json(body)? indents and colours JSON.

Show data:

use tinsel::{Border, Table, badge, palette};

Table::new(["service", "status", "p95"])
    .row(["api".to_string(), badge(palette::SAGE, "healthy"), "84ms".into()])
    .row(["auth".to_string(), badge(palette::AMBER, "slow"), "1.2s".into()])
    .sort_by_desc(2)           // by value: 1.2s before 84ms
    .border(Border::Rounded)
    .print();

Full-screen apps: dashboards, pickers, little toys. Write a struct, draw it in view, change it in event; app::run takes over the screen and gives it back afterwards (even on a panic). Panels shimmer when focused, lists scroll themselves, and numbers can be drawn big:

use tinsel::app::{self, App, Frame, Panel, Plot, Stat, Size::*};

struct Dash { latency: Vec<f64> }

impl App for Dash {
    fn view(&self, frame: &mut Frame) {
        let [stat, chart] = frame.area().columns_gap(1, [Fixed(20), Fill(1)]);
        frame.render(stat, Panel::new("p95").body(Stat::new("latency", "84ms")));
        frame.render(chart, Panel::new("latency").body(Plot::new(&self.latency)).focused(true));
    }
}

app::run(Dash { latency: vec![84.0, 90.0, 120.0, 340.0, 95.0] })?;   // q or Esc quits

A full-screen dashboard drawn with tinsel: four big-number stats, a list of services with the worker chosen, a latency chart, resource meters and a table of regions

Grid is a table with a cursor, for lists you move through: rows can sit under group headings, a panel can say where its data came from on its top border, and tabs can carry their own colour and a mark:

A services dashboard drawn with tinsel: groups on the left, a table of services grouped under core, data and edge with one row chosen, staging and production tabs, and details for the chosen service

Whole programs fit too: tvim is a vim-like text editor built on tinsel's full-screen apps:

Anything tinsel draws (tables, trees, cards, any Block) goes straight into a panel, next to List, Tabs, Plot, Stat, big text, hints and twinkling Sparkles. app::snapshot(&app, 80, 24) draws a frame without a terminal, for tests, and Frame::html() (or Block::html()) turns one into a web page that looks just like it, for screenshots.

Report an error with its whole cause chain:

tinsel::Report::from_error("couldn't start", &err)
    .hint("create app.toml, or pass --config <path>")
    .eprint();
  ✕  couldn't start
     ╰─ couldn't read app.toml
        ╰─ No such file or directory (os error 2)
  →  create app.toml, or pass --config <path>

…and point at the problem:

Report::new("couldn't read app.toml")
    .cause("port must be a number")
    .code(Code::around(&config, 3, 1).path("app.toml").caret(8, 8, "not a number"))
    .eprint();
  ✕  couldn't read app.toml
     ╰─ port must be a number
       ╭─ app.toml:3
     2 │ host = "0.0.0.0"
     3 › port = "eighty"
       │        ^^^^^^^^ not a number
     4 │ workers = 4

Panics, drawn the same way, with the terminal put back first:

fn main() {
    tinsel::install_panic_hook();
    // …
}

For scripts and tools, one switch from a --json or --quiet flag:

tinsel::set_output(tinsel::Output::Json);   // or TINSEL_OUTPUT=json
{"event":"step","title":"deploy","step":"Build","path":["Build"],"state":"done","secs":1.204}
{"event":"error","title":"couldn't start","causes":["couldn't read app.toml"],"code":[],"hint":"…"}

When stdout isn't yours, because it carries a command's output or data for another program, draw on stderr instead:

tinsel::set_target(tinsel::Target::Stderr);   // or TINSEL_TARGET=stderr

See it

cargo run -- showcase              # every component, then a live deploy
cargo run -- showcase table        # one section
cargo run -- showcase --accent blue  # in another accent; --theme light, --json and --quiet work too
cargo run -- demo --bar waveform     # the deploy with waveform progress bars
cargo run -- help                  # the CLI's own help, with its entrance
cargo run -- prompts               # the interactive questions
cargo run -- timings               # what Live has learned about your step durations

The examples are small and meant to be copied. Run any of them with cargo run --example <name>:

example what it shows
hello the smallest useful program: a spinner around some work, then a message
deploy a live step list that closes with a card; -- --fail to see a step fail
parallel steps at the same time, with sub-steps, a log line and a panic hook; -- --json for the same run as JSON
status a read-only status command: a table, details, a chart and a tree; pipe it to cat for plain text
questions asking questions, and handling Ctrl-C partway through
form questions asked as one form, going back and looking the answers over
cli reading flags, arguments and subcommands, with --help from the same description; -- --help or -- stauts
errors a Rust error turned into a report with its whole cause chain
dashboard a live full-screen dashboard: stats, a service list, a chart that follows the selection, logs
services services by group with a column per environment, a filter, dialogs and toasts

What's in it

live work Live step lists with sub-steps, parallel steps and log · skipped, cancelled and waiting steps · Region for any block · commands as steps with timeouts and retries · timeline · spin / try_spin · Progress with rate and time left, unknown or growing totals · .progress() on any iterator · bars as a line or a waveform · seven Spinners (sparkle twinkles, and is the default)
messages success · info · warn · error · hint · counter · title · rule · callout · Report (with code excerpts)
data Table (numbers right-align and sort by value, units and all; borders, wrapping, footers, highlighted rows) · Tree · pairs · columns
charts sparkline · bars · meter · histogram · heatmap
code diff · Code excerpts with syntax colouring (Rust, TOML, JSON, YAML, shell, Python, JS), a highlighted line and a caret under the problem
documents markdown (and markdown::wrapped) · json · Help with an animated entrance · Block::page
inline badge · link (clickable) · Card · paint, paint_on, paint_bg, bold, dim, italic, underline · style::gradient · anim for shimmering labels, moving bars and values that glide into place (Glide, Glider)
apps app::run full-screen apps, drawn only when something changes or a frame asks (animate, animate_at, redraw_at) · Panel · List · Grid · ScrollView · TextInput (with a History and its own idea of a word) · TextArea · Scrollbar · Tabs · Plot · Stat · big · hints · Sparkles · Rect layout with rows / columns · keys with their modifiers, read and written in vim's notation (<C-a>) and shown as symbols (⌃A), mouse and resize events · Job for work on another thread · app::snapshot for tests · Frame::html for screenshots
command line Cli for flags, options, arguments and subcommands · --help and --version for free · mistakes as a Report with "did you mean" · value_as for typed values
questions prompt::confirm · input / Input (validation, placeholders, line editing) · password · number · date · select / Select · multiselect / MultiSelect (filter as you type, headings, disabled options with a reason, validation) · Dropdown for long lists (notes, badges, your own answer) · .back() to go back a question · Form to ask several, then look the answers over · editor · suggestions and path completion · confirm_typing
setup install_panic_hook · set_output (Json, Quiet) · set_target (stderr) · set_focus · set_history · set_accent · set_theme · set_color_mode · set_fps · set_ctrl_c · timings
helpers text::{width, width_with_tabs, pad, truncate, truncate_start, wrap, strip_ansi, content_width, fuzzy, highlight} · terminal_width · format::{bytes, duration, count, grouped, ago, ago_long, plural, local_clock} · clipboard::{copy, paste} (system tools, or OSC 52 over ssh)

Full reference with examples for every item: docs.rs/tinsel.


Testing what you print

Catch everything your own code prints through tinsel, as it would come out into a pipe: messages, steps, spinners, tables and errors, in order, without colour:

#[test]
fn deploy_says_where_it_went() {
    let printed = tinsel::capture(|| my_cli::deploy("production"));
    assert!(printed.contains("●  deployed to production"));
}

One piece on its own needs no capturing: .plain() gives any block's text.

#[test]
fn status_table() {
    let table = tinsel::Table::new(["app", "size"]).row(["core", "34 MB"]);
    assert_eq!(table.lines().plain().lines().last(), Some("  core   34 MB"));
}

For the colour codes themselves, tinsel::with_color_mode(ColorMode::TrueColor, || …) turns colour on for that closure, on that thread alone, so tests beside it aren't affected.

A Live display can run headless, on a clock that only moves when you say:

#[test]
fn deploy_shows_the_build_time() {
    tinsel::set_color_mode(tinsel::ColorMode::None);
    let live = tinsel::Live::headless("deploy", "my-app");
    let build = live.step("Build");
    build.start();
    live.advance(std::time::Duration::from_millis(1200));
    build.done();
    assert!(live.snapshot().plain().ends_with("1.2s"));
}

Things it does on its own

Estimates from history. Live steps remember their durations in ~/.cache/tinsel (or $XDG_CACHE_HOME/tinsel), one small file per program. A step with no progress of its own gets an estimate bar from its recent median, and says slower than usual when it is. Only successful steps on a terminal are recorded. Live::remember_as("name") picks the file, .no_history(), tinsel::set_history(false) or TINSEL_NO_HISTORY=1 (any value but an empty one) turns it off. tinsel::timings(Some("my-app")) shows what's been learned, and flags a step whose last run was unusually slow.

Focus. In terminals that report window focus (iTerm2, kitty, WezTerm, Ghostty, Alacritty, foot, …), animation slows while you're away, a run of 10s or more that finishes while you're away sends a notification (.notify_after(…), .no_notify()), and returning re-twinkles what finished. Keys typed during a run are held back from the display and handed to the shell afterwards. .no_focus(), tinsel::set_focus(false) or TINSEL_NO_FOCUS=1 turns all of this off, and leaves stdin alone. tinsel::notify sends a notification yourself.

Tall displays. A Live display taller than the terminal leaves its top rows in scrollback and keeps redrawing what fits, so long step lists don't scramble the screen.

Theme. Decided once from TINSEL_THEME=light|dark, then COLORFGBG, then by asking the terminal for its background colour. Override with tinsel::set_theme.

Accent. Pink unless TINSEL_ACCENT (violet, blue, teal, orange, or a hue in degrees) or tinsel::set_accent says otherwise. Every pink moves, including the faint tint in the greys; red, amber and sage keep their meaning.

When it decides wrong, tinsel doctor says what it decided and why (colour off: stdout isn't a terminal, theme light: COLORFGBG=0;15) and warns about any setting it can't use, like a misspelt TINSEL_THEMES or TINSEL_OUTPUT=jsn. tinsel::doctor() gives you the same report, to print from a --debug-terminal flag of your own.


Platform notes

Everything works on macOS, Linux and Windows. Ctrl-C puts the cursor and the terminal back everywhere.

  • Raw mode on Unix shells out to stty, to stay free of dependencies. Prompts, Keys and full-screen apps need it, so a minimal container without coreutils can't read single keypresses (everything that only draws still works).
  • Terminal size comes from ioctl on macOS and Linux. Other Unixes, the BSDs among them, fall back to $COLUMNS and $LINES, then 80×24.
  • Widths follow the Unicode 17 tables built into tinsel, so CJK, emoji and combining marks line up without a lookup at run time.
  • Windows uses the console API for keys and size (Windows Terminal or a Windows 10+ console). Focus awareness and background detection need a terminal that answers, which there means Windows Terminal; the older console quietly goes without rather than wait for answers that never come.
  • Colour is truecolor when COLORTERM says so, the 16 basic colours when TERM names a terminal without 256color, and 256 colours otherwise. NO_COLOR, FORCE_COLOR and CLICOLOR are respected.

Stability

tinsel follows semantic versioning from 1.0: nothing public changes in a way that breaks your code without a new major version. Enums and structs that are likely to grow are #[non_exhaustive], so a new key, colour mode or event can arrive in a minor release; match them with a _ arm.

The minimum supported Rust version is 1.85. Raising it is a minor release, not a major one, and is said so in the changelog.


Contributing

Issues and pull requests are welcome. tinsel is small on purpose: no dependencies, one visual language, and every component reads well as plain text too. CONTRIBUTING.md has the ground rules, the commands CI runs and how commits become the changelog.

License

MIT