moonetui

    A terminal UI toolkit for MoonBit: cell buffer, differential ANSI renderer, incremental key parser, layout, a CSS-like design system, fifty-four widgets, and drivers for terminals, Node, browsers and serial lines.

    tui
    terminal
    terminal-ui
    tui-framework
    cli
    console
    widget
    widgets
    dashboard
    form
    table
    tree
    chart
    slider
    calendar
    pagination
    command-palette
    diff
    hex-dump
    ansi
    truecolor
    escape-sequences
    unicode
    layout
    css
    design-system
    node
    browser
    wasm
    serial
    moonbit
    Download zip
    Version
    0.4.1
    License
    Apache-2.0
    Last updated
    18 hours ago
    Downloads
    162

    #MoonBit Easy Terminal UI Frame

    moonetui · a terminal UI toolkit for MoonBit

    Cell buffer · differential ANSI renderer · incremental key parser · layout · CSS-like design system · 55 widgets · drivers for terminals, Node, browsers and serial lines

    Check and Test Docs mooncakes licence

    #Highlights

    Synchronous coreNo async and no hidden event loop. The host calls one step(): poll, parse, dispatch, lay out, compose, diff, write.
    Differential rendererTwo frames become the runs of cells that changed, and only the escape sequences needed to draw them. A widget that moved its cursor redraws its own rows and leaves the rest of the screen standing.
    A CSS-like design systemSelectors over name, id, class and :focus, :hover, :disabled, stacked by specificity and cascade, with inheritance, borders, padding, margins, docks, grid spans and transitions.
    Unicode-awareEvery line is measured in terminal columns over a generated width table: wide CJK, double-width emoji, combining marks.
    Four backendsThe same code and the same test suite on wasm, wasm-gc, js and native.
    Any wireA modern terminal with true colour, a serial-era terminal with eight colours, a browser canvas, or a bare UART with no cursor addressing at all.

    #Quick start

    moon add moonbitstack/moonetui

    moon run --target native src/examples/gallery # every widget and every style, live moon run --target native src/examples/monitor # a complete app: tabs, timers, a command line moon run --target native src/examples/snake/main # a game: arrows turn, space pauses moon run --target native src/examples/life/main # Conway's life, a generation a frame moon run --target native src/examples/game2048/main # 2048: arrows slide, r restarts moon run --target native src/examples/pulse/main # a dashboard: a window of load moon run --target native src/examples/donut/main # a torus, turning in two axes moon run --target native src/examples/files/main # a browser in Miller columns moon run --target native src/examples/top/main # cores, memory, network, processes moon run --target native src/examples/git/main # branches, commits, files moon run --target native src/examples/read/main # a Markdown page, set with type moon run --target native src/examples/invaders/main # a block that marches, a gun that shoots moon run --target native src/examples/blocks/main # seven pieces, a ten by eighteen board moon run --target native src/examples/sweep/main # mines, flags, and a region that opens moon run --target native src/examples/sudoku/main # nine by nine, a clash marked moon run --target native src/examples/cards/main # Klondike: seven columns, four foundations moon run --target native src/examples/board/main # a dashboard of small panels moon run --target native src/examples/boxes/main # containers, their stats, and a live tail moon run --target native src/examples/prs/main # pull requests, checks, a merge moon run --target native src/examples/tunes/main # a player: spectrum, needle, album moon run --target native src/examples/drift/main # a trader on six ports, with a chart moon run --target native src/examples/mon/main # a route, a party, a wild thing in the grass moon run --target native src/examples/logs/main # a tail, a level filter, a typed query moon run --target native src/examples/json/main # a document as a tree: a path, folds, a query moon run --target js src/examples/hello # under Node moon run --target native src/examples/uart # whole frames of plain text, as a serial line gets them moon run --target native examples/dbmux/src/main -- --demo # a database client, with a SQLite demo database moon run --target native examples/mbtjj/src/main # a Jujutsu client, read from the repository you run it in

    src/examples/dbmux/ holds the screen the tui example runs, in a package of its own: a main package cannot carry tests the checker accepts, and the frame tests drive the same tree the example does.

    examples/ holds two programs, each a module of its own:

    • examples/mbtjj/ — a client for Jujutsu: the log with its graph, the change under the cursor, what it does and the operations the repository has seen. It runs jj for its answers, so it works on any repository and writes nothing. moon run --target nativeexamples/mbtjj/src/main opens the one you are in; --demo shows a captured log where no repository is at hand.
    • examples/dbmux/ — a database client: a table list, an editable grid, a modal SQL editor, a command palette, and one connection per engine. moon run --target native examples/dbmux/src/main -- --demo opens a SQLite database in memory, so it runs with nothing installed.

    Both are examples in the sense that matters — nothing in them reaches past what this library publishes, so any part of them can be copied into a program of your own — and both do the real thing, against a real repository and real servers. Each has its own README with the keys, the options and what it does not do.

    The gallery runs in a browser too: moon build --target js, serve the repository root, and open src/examples/browser/index.html.

    A first application: a list, a field, and a stylesheet that frames the list and thickens the frame while it has focus. It runs on a terminal, so the block below is native only.

    fn main raise {
    let sheet = @design.Stylesheet::new()
    sheet.add(
    @design.Sel::new(name="Header"),
    @design.Styles::new(text=@style.Style::new(bold=true, fg=@style.cyan)),
    )
    sheet.add(@design.Sel::new(classes=["framed"]), @design.Styles::new(border=Round))
    sheet.add(
    @design.Sel::new(classes=["framed"], focus=true),
    @design.Styles::new(border=Heavy),
    )
    let list = @widget.ListView::new(["alpha", "beta", "gamma"])
    let field = @widget.Input::new(placeholder="pick one")
    let line = @layout.Box::new(extent=Cells(1))
    let tree = @app.column(0, [
    @app.leaf(1, @widget.Header::new("moonetui"), box=line, name="Header"),
    @app.leaf(2, list, classes=["framed"]),
    @app.leaf(3, field, box=line),
    @app.leaf(4, @widget.Footer::new([("tab", "next"), ("enter", "choose")]), box=line),
    ])
    let ui = @app.App::new(@native.NativeTty::new(), tree, sheet~)
    ui.start()
    @native.run(() => {
    let alive = ui.step()
    for report in ui.drain() {
    if report is Selected(index~, ..) {
    field.set(list.items()[index])
    ui.refresh()
    }
    }
    alive
    })
    ui.stop()
    }

    Its moon.pkg imports app, design, driver/native, layout, style and widget from moonbitstack/moonetui, and declares supported_targets = "native".

    #The widget inventory

    GroupWidgets
    Text and displayStatic and label(), Header (with a Clock), Footer, Rule, Digits, Sparkline, Progress, LoadingIndicator, Placeholder, Pretty, Link, KeyPanel
    Entry and logsInput, TextArea, Log, RichLog, MaskedInput
    ChoicesSwitch, Checkbox, RadioButton, RadioSet, OptionList, SelectionList, Select, Slider, Calendar
    Navigation and structureButton, ListView, Paginator, Tabs, TabbedContent, Collapsible, Tree, DirectoryTree, ContentSwitcher, StatefulList, StatefulTable
    Data and noticesDataTable, HexView, Diff, Markdown, Tooltip, Toast
    DialogsMessageBox, InputBox, FileDialog
    Menus and commandsMenu, MenuBar, CommandPalette
    Charts and metersChart (lines and scatter), BarChart, Gauge, Scrollbar, Canvas (Braille dots)
    DecorationBlock — a frame, title and padding that wraps any widget

    Each one has its keyboard contract, message shape and tests, and a live demo on the documentation site beside its source.

    #Package map

    PackageWhat it does
    @geomInteger rectangle algebra: Offset, Size, Region, Spacing
    @styleColours (named, indexed, true colour), attributes, palette quantisation, differential SGR
    @stripOne rendered line: styled segments measured in terminal columns
    @eventKeys, mouse reports, paste, resize and focus as plain values
    @inputThe terminal byte stream turned into events
    @compThe compositor: placements to rows, rows to changed spans, spans to escape sequences
    @driverThe seam to a terminal, and a headless terminal for tests
    @vtA virtual terminal: the screen an escape stream draws, for the browser driver, tests and screenshots
    @layoutSizes along an axis, the grid with spans and gutters, and anchored, pivoted placement
    @designRules over name, id, class and state; borders, padding, margins, alignment, docks, offsets, transitions, and the semantic Theme
    @widgetThe widget contract and the inventory
    @appThe widget tree, focus ring, scroll containers, docks, grids, screens, timers and the frame loop
    @driver/native · @driver/node · @driver/webA real terminal through the C library; Node; a canvas in the browser
    examples/themeThe look the examples share: one palette, one sheet, the header and key bar every screen wears
    examples/snake · examples/life · examples/game2048Three games, each with the frame test that plays it
    examples/pulseA dashboard: a rolling window drawn as a spectrum, a rate, and a hold
    examples/donutA torus sampled, turned and shaded into characters, with a z-buffer
    examples/filesMiller columns: where from, what is here, what the selection holds
    examples/topFour regions: cores, memory, two network charts, the busiest processes
    examples/gitThree panes with a tab between them, and a file that stages
    examples/readMarkdown set with type: headings, bullets, code, quote, table, scrollbar
    examples/invadersTwenty-four invaders marching, one bullet in the air, three lives
    examples/blocksSeven pieces turning in a four by four box, rows that clear, a level that rises
    examples/sweepTen by ten of mines: reveal, flag, and a zero that opens its region
    examples/sudokuNine by nine: givens that hold, digits that go in, a clash marked
    examples/cardsKlondike on green felt: a run lifted from a column, a card sent home
    examples/boardSix framed panels: a big clock, the month, tasks, commits, load, the day
    examples/boxesA container client: a list of boxes, one opened, its log running below
    examples/prsPull requests with their checks, a card for the chosen one, a merge
    examples/tunesA record playing: a spectrum, a needle, the album behind it
    examples/driftSix ports on a chart: prices, a hold, fuel, and a logbook
    examples/monA route to walk, a party of three, and fights in the tall grass
    examples/logsA log tail: levels to switch off, a typed filter, a map of the file
    examples/jsonA document as a tree beside the node it holds, its path, a typed query

    #Standards

    • Unicode: rendering is measured in terminal columns over a generated width table.
    • ECMA-48 / ISO 6429: SGR (CSI … m) for attributes, CUP (CSI H) for addressing, ED and EL for erasing.
    • UTF-8: the input decoder is incremental, so a code point split across two reads arrives whole.

    #Tests

    moon check --target all --deny-warn moon build --target all moon test --target all moon fmt && moon info --target all # the diff must stay clean

    710 tests per backend, the same suite on wasm, wasm-gc, js and native, run on Ubuntu, macOS and Windows in CI. Every widget asserts the rows it draws, and every demo draws in a headless application.

    #Conformance

    Where something outside this library defines the answer, the answer is checked against that definition, and the checks live in the repository: moon test needs nothing but the toolchain.

    WhatHeld toVectors
    Columns per code pointwcwidth 0.9.4 against CPython's unicodedata read through UAX #11every code point these two speak for: 291,782
    Grapheme clusterstwo independent implementations of UAX #29, uniseg and regex, for where a cluster starts, and wcwidth for its columns48 strings: marks, conjuncts, joiner sequences, flags, keycaps, wide forms
    Keysthe terminfo entries of xterm, screen, tmux, the Linux console, rxvt, vt100 and ansi168 sequences across eight terminals
    Framesthe bytes a frame is drawn with, read back by pyte and by tmux5 frames: attributes, wide characters, joined emoji, widgets, a redraw
    A demo's keysthe screen after each key, read back by pyte and by tmux8 frames: open, tab, two downs, enter, tab, a typed key, ctrl-c
    A game's framesthe screen after each move, read back by pyte and by tmux6 frames: open, moving, ate, paused, over, again

    scripts/gen_conformance.py writes the three vector files; scripts/verify_terminals.py hands the frame bytes to both emulators and compares the screens. The frame lines are printed only when MOONETUI_INTEROP is set, so moon test on its own prints a report rather than a screen's worth of hex:

    MOONETUI_INTEROP=1 moon test --target native -p moonbitstack/moonetui/app \ | grep '^interop' | python3 scripts/verify_terminals.py --in /dev/stdin

    scripts/render_frame.py turns a frame into a picture — one frame, or a grid of them taken from several examples, since every example announces its frames the same way:

    MOONETUI_INTEROP=1 moon test --target native -p moonbitstack/moonetui/examples/board \ | grep '^interop' | python3 scripts/render_frame.py --pick board/00 --out board.png

    The screen src/examples/dbmux holds is the one examples/dbmux/src/main runs: a test drives the same tree with a scripted driver — tab, two downs, enter, tab, a character, ctrl-c — asserts what each key did to the list, the bar and the field, and announces every frame, so a key that lands on the wrong widget fails moon test before an emulator is asked anything. Nothing is outstanding: no code point, cluster, key or frame in the vectors disagrees with its references.

    Two places where the references disagree with each other, or with the way a terminal draws a mark, are recorded in the vectors rather than argued about: a code point whose width the two references read differently is written with -1 and not asserted, as is the column count of a string holding a spacing mark, whose cell this library draws inside the cluster and wcwidth counts on its own. The boundaries of those strings are still held to.

    #Licence

    Apache-2.0. See LICENSE.