flatte

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 37 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Flatte logo

Flatte

ci Go Reference Live demo

Flatte is a Go TUI foundation built around one mutable state struct, direct state mutation, and pure views. It is intentionally not a Bubble Tea clone: apps do not define messages, commands, or component update trees. State lives in your app, Handle mutates it, and View renders it.

A montage of Flatte sample apps running in the terminal

A glimpse of the sample apps — Snake, a Docker-style TUI, a three-pane workspace, styling, tables, progress — all built from the primitives below. Try Flatte live in your browser → · regenerate the reel with cmd/record-demo.sh.

The module path is currently:

go get github.com/lunguini/flatte

The root package name is flatte, so ordinary imports use the flatte identifier:

import "github.com/lunguini/flatte"

Where it runs

One App[S] runs in every host below; the host is chosen when you call flatte.Run, not in your app code.

Host How to select it Status
Terminal (macOS, Linux) flatte.Run(ctx, app) Supported
Terminal (Windows) flatte.Run(ctx, app) Tested in CI; a real-console check is still recommended
macOS window flatte.Run(ctx, app, window.Options{}) Supported, no cgo
Browser, terminal look flatte.Run built with GOOS=js GOARCH=wasm Supported (Go and TinyGo)
Browser, GUI look on a canvas window.Options built for js/wasm Supported; no menu bar, context menus, extra windows, or file dialogs yet
Windows and Linux windows window.Options Not yet: falls back to the terminal

window.Supported() reports whether the GUI host is available in the current build. See One app, three hosts for the setup of each.

Minimal App

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/lunguini/flatte"
)

type State struct {
	count int
}

func Handle(s *State, ev flatte.Event, fx flatte.Effects[State]) {
	key, ok := ev.(flatte.KeyEvent)
	if !ok {
		return
	}
	switch key.Key {
	case flatte.KeyEscape:
		fx.Quit()
	case flatte.KeyCharacter:
		switch key.Rune {
		case '+':
			s.count++
		case '-':
			s.count--
		case 'q', 'Q':
			fx.Quit()
		}
	}
}

func View(s *State, ctx flatte.RenderContext) flatte.Frame {
	return flatte.Frame{Content: fmt.Sprintf("count: %d\n\n+/- change  q quit", s.count)}
}

func main() {
	if err := flatte.Run(context.Background(), flatte.App[State]{
		State:  &State{},
		Handle: Handle,
		View:   View,
	}); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Mental Model

  • State is the single source of truth.
  • Handle(state, event, effects) mutates state directly.
  • View(state, context) returns a full flatte.Frame.
  • Async work goes through named helpers: flatte.Go, flatte.Every, flatte.Stream, and flatte.Latest.
  • Widgets in flatui are opt-in state structs. They own no goroutines and no key policy.
  • Tests use normal field assertions plus flatest golden/harness helpers.

Current terminal input scope

Flatte currently delivers key presses (including F1–F12), paste, focus, mouse, clipboard, and resize events through its closed Event set. Key release events and terminal capability/keyboard-enhancement reports are not delivered. Composite or IME text is currently reduced to the first rune of a key event. PasteEvent preserves multi-rune pasted strings, but it is not an IME substitute; applications requiring composition must wait for a dedicated text-input API.

Inline rendering cannot be combined with mouse reporting: Run returns ErrInlineMouseUnsupported. Inline frames can move as scrollback is printed, so Flatte does not claim frame-relative mouse coordinates in that mode.

ResizeEvent is emitted initially. On Unix, later terminal resizes arrive via SIGWINCH; on Windows, ultraviolet receives console window-size events from a real Windows console. The repository's Windows checks compile and run tests, but piped input is not evidence of live console-resize behavior; verify that path in an actual Windows console before relying on it operationally.

The repository includes an opt-in real-console gate. In PowerShell on Windows, build the test binary, run it directly, and resize the console once:

go test -c -o flatte-resize-smoke.exe .
$env:FLATTE_WINDOWS_RESIZE_TTY = "1"
.\flatte-resize-smoke.exe -test.run TestWindowsConsoleResizeTTY -test.v

Packages

  • github.com/lunguini/flatte (flatte) - runtime, events, effects, frame, cursor, clipboard, exec, file selection. flatte.Run uses the native terminal by default and mounts a browser page on js/wasm.
  • github.com/lunguini/flatte/flatui - stateful UI helpers such as TextField, Textarea, Viewport, List, Table, Tree, FocusRing, Paginator, Progress, Spinner, Timer, and Stopwatch.
  • github.com/lunguini/flatte/flatui/layout - flexbox-style layout engine (Row, Col, Scroll, Label, Input, Text, Spacer) that solves a frame tree once into composed content plus per-ID rects for geometry-based hit-testing; return the tree as Frame.Root and the runtime composes it and fills MouseEvent.Target. The same tree solves in points for GUI backends (LayoutScene).
  • github.com/lunguini/flatte/flatest - deterministic app driver, golden assertions, frame rendering, and replay helpers.
  • github.com/lunguini/flatte/window (separate module) - runs the same app in a native window with real text and components (macOS, no cgo), or with the same look on a browser canvas in js/wasm builds. Select it through the shared entry point: flatte.Run(ctx, app, window.Options{}). On unsupported platforms window.Options installs no host; use window.Supported() to show a native-window flag only where available.
  • github.com/lunguini/flatte/window/media - media.Controls{} opts a macOS terminal run into system Now Playing controls. It is safe alongside window.Options; the window host connects media when App.NowPlaying is set.

Custom drivers implement the small host contract in the root flatte package; see Writing a host.

Navigation Patterns

Use plain state:

  • Multiple full screens: store a screen enum in State and switch in Handle and View. See cmd/flat-pages.
  • Multiple focusable sections on one screen: store a flatui.FocusRing. See cmd/flat-workspace.
  • Modal/overlay state: store modalOpen bool and modal-specific fields. See cmd/flat-modal.

Useful Commands

The library and samples are separate modules:

go test ./...
go vet ./...

cd cmd
go test ./...
go run ./flat-pages
go run ./flat-workspace

Thanks

Flatte stands on a lot of excellent open-source work:

  • Charm — Flatte is the deliberate inverse of Bubble Tea, but it happily reuses Charm's MIT-licensed substrate: Lip Gloss for styling, Ultraviolet for input parsing and cell-buffer rendering, and x/ansi and colorprofile underneath. Bubble Tea also serves as our honest benchmark — the cmd/bubble-* comparison apps keep our claims grounded. Thank you, Charm team.
  • rivo/uniseg for correct Unicode grapheme segmentation, so cursors and widths behave.
  • The Go team for the language, golang.org/x/term, and first-class WebAssembly support that powers the browser demo in cmd/flat-landing.

Further Reading

  • Quick Reference maps common TUI needs to Flatte APIs.
  • One app, three hosts shows the terminal, native window, and browser setup.
  • Examples maps every sample app to the capability it demonstrates.
  • Contributing covers Conventional Commits, the quality bar, and the golden-snapshot policy.
  • Changelog is generated from commit messages on each release.

Roadmap

Flatte is pre-1.0. Planned work, roughly in order:

  • Windows and Linux windows. window.Options currently opens a window only on macOS; elsewhere it falls back to the terminal. Native hosts for Windows and Linux are planned; until then, treat the GUI as macOS and browser only.
  • Windows terminal verification. The Windows build runs the test suite in CI, but resize and input are still to be checked in a real Windows console (see Current terminal input scope).
  • Browser canvas parity. Menu bar, context menus, secondary windows, and file dialogs on the canvas host, and a smaller wasm download.
  • API stabilization toward 1.0, driven by feedback from apps built on Flatte.

Compatibility and current limits

Flatte is pre-1.0. The public packages follow Go module versioning, and breaking API changes are called out in the changelog; the API snapshot test is a regression guard, not a promise that every 0.x release is source-compatible. Ultraviolet and Lip Gloss are implementation dependencies: applications use Flatte's events, frames, and layout types rather than substrate types.

The deprecated raw-channel Async bridge was removed in the 2026-08 breaking stabilization increment; use Go or off-loop Effects.Send. Use flatest.Start for app-level tests and flatest.NewHarnessEffects for callback-level tests that pass Effects directly to Handle.

Public widget dimensions clamp to 0..65,536 cells. SaveState syncs the file before replacement and additionally syncs the containing directory on Unix; use LoadStateWithError when corrupt state must be preserved rather than silently replaced by defaults.

See Current terminal input scope for the current input and resize limitations. Apps should size scrollable content with flatui.Viewport, return layout trees as Frame.Root so mouse events carry Target/TargetRect, and adopt solved geometry into widget state from LayoutEvent, which the runtime delivers before painting.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInlineMouseUnsupported = errors.New("flat: WithInline cannot be combined with mouse reporting")

ErrInlineMouseUnsupported reports an invalid combination of options. Inline frames do not have a stable terminal origin, so mouse coordinates cannot be translated to frame-relative positions. Use alternate-screen rendering for mouse-enabled apps.

View Source
var ErrInvalidInterval = errors.New("flat: interval must be positive")

ErrInvalidInterval is returned by Every and ScopeEvery when interval is zero or negative.

View Source
var ErrMultipleHosts = errors.New("flatte: multiple host options selected")

ErrMultipleHosts reports that more than one host-installing option was supplied to Run.

View Source
var ErrNoDialogs = errors.New("flatte: this host shows no dialogs")

ErrNoDialogs is the error OpenFile and SaveFile answer with on a host that cannot show dialogs (a zero Effects value, or a harness without them).

View Source
var ErrNoSelection = errors.New("flat: no file selected")

ErrNoSelection is returned by SelectFile when the selector command exits successfully without printing a selected path.

View Source
var ErrUnsupported = errors.New("flatte: effect unsupported by this host")

ErrUnsupported reports that the current host cannot perform an effect.

Functions

func Alert added in v0.2.0

func Alert[S any](fx Effects[S], name string, d AlertDialog, fold func(s *S, button int, err error))

Alert shows a message with buttons and folds the chosen button's index into state as one update named name. A dismissed alert has button -1; a host without dialogs reports ErrNoDialogs. Call it from Init, Handle, or a fold.

func ApplyUpdate

func ApplyUpdate[S any](s *S, tracer Tracer, update StateUpdate[S])

func Cancel

func Cancel[S any](fx Effects[S], name string)

Cancel stops in-flight Latest work under name, if any. It does not affect Every tickers — those stop through the Scope that started them (see Every's doc).

func Every

func Every[S any](fx Effects[S], name string, interval time.Duration, fold func(*S, time.Time)) error

Every sends a named update on a fixed interval until the loop context is cancelled. Timing comes from the Clock (real ticker by default; a fake clock drives it deterministically under test). It returns ErrInvalidInterval when interval is zero or negative and does not register a ticker.

Every has no name-based cancellation of its own — Cancel only stops Latest work. To stop or re-arm a ticker (pause/resume, changing the interval), start it through a Scope (ScopeEvery) and cancel the scope; flat-game dogfoods exactly this for pause/resume/restart.

func Exec

func Exec[S any](fx Effects[S], name string, cmd *exec.Cmd, fold func(*S, error))

Exec releases the terminal (cooked mode, main screen), runs cmd attached to it, restores the terminal, and applies the named fold with the command's error — all synchronously on the loop goroutine: the TUI is paused while cmd runs, exactly like shelling out to $EDITOR. cmd's stdin/stdout default to Run's input/output and stderr to os.Stderr, each only when unset. Loop-goroutine-only, like all effects; no-op on a zero Effects value.

func Go

func Go[S, T any](fx Effects[S], name string, work func(context.Context) (T, error), fold func(*S, T, error))

Go runs work off-loop and folds its result back into state as one named update through Effects-owned context and transport. A zero Effects value has no update transport, so Go does not start work on it.

func Latest

func Latest[S, T any](fx Effects[S], name string, work func(context.Context) (T, error), fold func(*S, T, error))

Latest is Go with supersede-by-name semantics: starting new work under a name cancels any in-flight work under the same name, and a superseded result is dropped even if it was already queued. This replaces manual generation counters for request/response races.

Without an update transport it does nothing. With a transport but no registry, it degrades to Go.

func LoadState

func LoadState[S any](path string, defaultState S) S

LoadState gob-decodes state from path, returning defaultState if the file is missing or fails to decode. Callers that later save unconditionally can overwrite unreadable evidence; persistent applications should use LoadStateWithError and refuse or explicitly quarantine corrupt state.

func LoadStateWithError added in v0.2.0

func LoadStateWithError[S any](path string, defaultState S) (S, error)

LoadStateWithError gob-decodes state from path while preserving I/O and decode errors for callers that need to distinguish a missing or corrupt state file from a valid file containing the zero value. The compatibility LoadState helper above intentionally retains its default-on-error behavior.

func OpenFile added in v0.2.0

func OpenFile[S any](fx Effects[S], name string, d OpenDialog, fold func(s *S, paths []string, err error))

OpenFile shows an open dialog and folds the chosen paths into state as one update named name: none when the user cancelled, with ErrNoDialogs on a host without dialogs. A window shows the system panel; a terminal draws a path prompt with a directory listing (one path, even when Multiple). Call it from Init, Handle, or a fold.

func Run

func Run[S any](ctx context.Context, app App[S], opts ...Option) (runErr error)

Run owns the selected host's event/update/render loop until the app quits or ctx is cancelled. Native builds use the terminal by default; an Option may select another host. js/wasm builds use the browser page by default.

func SaveFile added in v0.2.0

func SaveFile[S any](fx Effects[S], name string, d SaveDialog, fold func(s *S, path string, err error))

SaveFile shows a save dialog and folds the chosen path into state as one update named name: "" when the user cancelled, with ErrNoDialogs on a host without dialogs. A window asks before replacing a file; a terminal does not (yet). Call it from Init, Handle, or a fold.

func SaveState

func SaveState[S any](path string, state S) error

SaveState gob-encodes state to path. The state struct must contain only gob-serializable fields — paths not open file handles, queries not DB connections. Anything live gets reopened on boot via a rehydrate step.

The file is written and synced beside the destination, then atomically renamed into place. Unix also syncs the containing directory; platforms without portable directory fsync still receive the file sync and rename. This keeps a previously valid state file intact when encoding or writing the new state fails (for example, when a state gains an unsupported gob field).

func ScopeEvery

func ScopeEvery[S any](scope *Scope, fx Effects[S], interval time.Duration, fold func(*S, time.Time)) error

ScopeEvery sends a named update on a fixed interval until the scope is cancelled. Timing comes from the Clock (real ticker by default; fake clock under test). A queued tick is discarded if the scope is cancelled before the loop applies it. It returns ErrInvalidInterval when interval is zero or negative and does not register a ticker.

func ScopeGo

func ScopeGo[S, T any](scope *Scope, fx Effects[S], work func(context.Context) (T, error), fold func(*S, T, error))

ScopeGo runs work off-loop using the scope's context. When the scope is cancelled, the context passed to work is cancelled. The fold runs on the loop goroutine as a named update. The update checks the scope again at apply time, so cancelling after enqueueing cannot run a stale fold.

func ScopeStream

func ScopeStream[S, T any](scope *Scope, fx Effects[S], source func(context.Context, func(T)), fold func(*S, T))

ScopeStream runs a long-lived source that emits many values over time. Each emitted value becomes one named update. When the scope is cancelled, both the source's context and the send-channel select see the cancellation; an update already queued at cancellation time is discarded on apply.

func SelectFile

func SelectFile[S any](fx Effects[S], name string, cmd *exec.Cmd, fold func(*S, FileSelection))

SelectFile releases the terminal, runs cmd as an external file selector, restores the terminal, and applies fold with the selected path. The selected path is read from stdout and trimmed. If cmd already has Stdout, output is still forwarded there while also being captured for the selection result.

This is intentionally terminal-delegated rather than an in-TUI file browser: apps can plug in fzf, yazi, ranger, or another command while Flatte owns the terminal handoff.

func Stream

func Stream[S, T any](fx Effects[S], name string, source func(context.Context, func(T)), fold func(*S, T))

Stream runs a long-lived source that emits many values over time; each emitted value becomes one named update. The source must return when its context is cancelled.

Types

type AlertDialog added in v0.2.0

type AlertDialog struct {
	Title   string
	Message string
	Buttons []string
}

AlertDialog is a message with buttons (nil: one "OK"). The first button is the default (Enter); Esc chooses a button labelled "Cancel".

type App

type App[S any] struct {
	State  *S
	Init   func(*S, Effects[S])
	Handle func(*S, Event, Effects[S])
	View   func(*S, RenderContext) Frame
	Tracer Tracer
	// OnExit is called after the loop ends, on every exit path (clean quit,
	// context cancel, signal). Use it to persist state before the process
	// exits. It fires before terminal restoration.
	OnExit func(*S)
	// Menus, when set, is the menu bar for the state, read like View after
	// every change: a window shows it natively, and every host delivers a
	// key matching an item's Keys as its MenuEvent (a terminal shows no
	// bar).
	Menus func(*S) []Menu
	// ContextMenu, when set, is the menu for a right-click on the ID'd node
	// target ("" outside any): a window shows it as a native popup, a
	// terminal draws it over the frame. Return nil for no menu (the click
	// is then delivered as usual); a shown menu consumes the click, and the
	// choice arrives as a MenuEvent with Target set.
	ContextMenu func(s *S, target string) []MenuItem
	// Windows, when set, declares the app's secondary windows for the
	// state, read like View after every change: a window appears when
	// declared and closes when no longer declared. View draws each (see
	// RenderContext.Window). A desktop host opens real windows; a terminal
	// draws them over the main frame.
	Windows func(*S) []Window
	// NowPlaying reports the current media item and the commands available
	// for it. A native host publishes it to the system media controls; nil
	// opts out. The callback is read on the app's state loop after changes.
	NowPlaying func(*S) *NowPlaying
}

type Capabilities added in v0.2.0

type Capabilities struct {
	Exec, Suspend, Print      bool // shelling out and releasing the terminal
	Alert, OpenFile, SaveFile bool // the dialogs the host can show
	Notifications, Clipboard  bool
	Drop                      bool // DropEvent for dropped files
	Mouse                     bool // mouse events arrive (WithMouse in a terminal or browser)
	Quit                      bool // Quit ends the program; false where it only stops the loop
}

Capabilities reports which effects and inputs the current host supports, so an app can hide what would only fail or do nothing. Each host fills it once; Effects.Capabilities and RenderContext.Capabilities report the same value. Effects the host lacks still answer: Exec with ErrUnsupported, dialogs with ErrNoDialogs.

type ClipboardEvent

type ClipboardEvent struct{ Text string }

ClipboardEvent delivers the terminal's answer to fx.ReadClipboard (OSC52, system selection). Unsupported terminals never answer — treat the event as optional and do not wait for it.

type Clock

type Clock interface {
	// Tick calls cb on each interval until ctx is cancelled. Real
	// implementations own a goroutine; fake ones fire synchronously.
	Tick(ctx context.Context, interval time.Duration, cb func(time.Time))
}

Clock abstracts the timing source for interval effects so tests can drive them deterministically. The real clock uses time.Ticker; flatest provides a fake one.

type Cursor

type Cursor struct {
	X, Y  int
	Style *CursorStyle
}

Cursor is a hardware-cursor position in frame cell coordinates.

type CursorShape

type CursorShape int
const (
	CursorShapeDefault CursorShape = iota
	CursorShapeBlock
	CursorShapeUnderline
	CursorShapeBar
)

type CursorStyle

type CursorStyle struct {
	Shape CursorShape
	Blink bool
	Color color.Color
}

CursorStyle configures the terminal hardware cursor when supported. A nil style leaves the terminal default in place.

type Desktop added in v0.2.0

type Desktop struct {
	Title string
	// Shortcut captures selected text only when explicitly invoked. Nil
	// disables global activation. Hosts report registration failure as a
	// DesktopEvent with Source "shortcut" and a nonempty Error.
	Shortcut *KeyEvent
}

Desktop configures an optional background status-menu utility in a window host. The existing app state, semantic Frame, and Menu declarations are shared with ordinary windows and terminal apps. Unsupported hosts may reject this option; importing flatte alone adds no native dependencies.

type DesktopCommand added in v0.2.0

type DesktopCommand struct {
	Kind     string
	Shortcut *KeyEvent
}

DesktopCommand requests show, hide, shortcut, or permission from a desktop utility host. Shortcut replaces global activation (nil disables it). Permission explicitly requests selection-capture permission; capture never prompts silently. Other hosts ignore these commands.

type DesktopEvent added in v0.2.0

type DesktopEvent struct{ ID, Text, Error, Source string }

DesktopEvent reports a native utility action. Source is service, shortcut, window, or host. Capture delivers selected Text or an Error; it never polls application contents. ID is "capture", "close", "permission", or a host failure identifier. Status-menu choices use the existing MenuEvent.

type Dialog added in v0.2.0

type Dialog struct {
	Open  *OpenDialog
	Save  *SaveDialog
	Alert *AlertDialog
}

Dialog is one dialog request as a host sees it: exactly one of Open, Save, and Alert is set. Host plumbing, not application API.

type DialogResult added in v0.2.0

type DialogResult struct {
	Paths  []string
	Button int
	Err    error
}

DialogResult is a host's answer to a Dialog: the chosen paths (none when cancelled) for Open and Save, the chosen button for Alert (-1 when dismissed). Host plumbing, not application API.

type DropEvent added in v0.2.0

type DropEvent struct {
	X, Y       int
	Target     string
	TargetRect layout.Rect
	Paths      []string
	Text       string
	// Window is the window it was dropped on ("" the main window).
	Window string
}

DropEvent reports files or text dropped on a window (a terminal turns a dropped file into a PasteEvent of its path instead). X, Y, Target, and TargetRect locate the drop as a MouseEvent's do; Paths are the dropped files, and Text is dropped text when there are none.

type Effects

type Effects[S any] struct {
	// contains filtered or unexported fields
}

func (Effects[S]) Capabilities added in v0.2.0

func (fx Effects[S]) Capabilities() Capabilities

Capabilities reports what the current host supports; the zero value on a zero Effects value or a harness that did not set any.

func (Effects[S]) Ctx

func (fx Effects[S]) Ctx() context.Context

Ctx returns the loop's context, defaulting to context.Background() if none is set (e.g., in tests using the zero Effects value). Use this to derive child contexts for scoped async work — context.WithCancel(fx.Ctx()) gives you a cancellable handle for per-screen or per-selection goroutines.

func (Effects[S]) Desktop added in v0.2.0

func (fx Effects[S]) Desktop(command DesktopCommand)

Desktop requests a native utility operation. Like Quit it is loop-only; workers send a named update whose fold invokes it. Safe on zero Effects.

func (Effects[S]) Notify added in v0.2.0

func (fx Effects[S]) Notify(n Notification)

Notify shows n outside the frame, and is fire and forget: there is no answer, and hosts and terminals without notifications ignore it. The framework never decides when to notify — an app that wants to only when it is not in front can track FocusEvent (WithReportFocus in a terminal; a window always reports it). Loop-goroutine-only, like Quit. Safe on a zero Effects value.

func (Effects[S]) Print

func (fx Effects[S]) Print(s string)

Print writes s into the terminal's scrollback above the live frame, then repaints the frame below it — the Claude-Code "message stream + pinned input" model: emitted lines flow into the real terminal's history (which the user scrolls with the terminal/mouse) while the frame stays put at the bottom. Requires inline rendering (WithInline); in alt-screen mode it is a no-op, because the prepended lines would be overwritten by the next frame. The content is the app's to format (no trailing newline is added). Newlines in s produce multiple scrollback lines. Loop-goroutine-only, like Quit. Safe on a zero Effects value. No-op on window and browser hosts.

func (Effects[S]) Printf

func (fx Effects[S]) Printf(format string, args ...any)

Printf is Print with fmt.Sprintf formatting.

func (Effects[S]) Quit

func (fx Effects[S]) Quit()

Quit requests a clean exit of the Run loop. Safe on a zero Effects value. Call it from Init, Handle, or a fold — they all run on the loop goroutine; calling it from an app-spawned goroutine is a data race.

func (Effects[S]) ReadClipboard

func (fx Effects[S]) ReadClipboard()

ReadClipboard asks for the clipboard content: the terminal via OSC52, or the window's pasteboard. A window or supporting terminal answers with a ClipboardEvent; unsupported terminals never answer — treat the event as optional and do not wait for it. Loop-goroutine-only, like Quit. Safe on a zero Effects value.

func (Effects[S]) Send added in v0.2.0

func (fx Effects[S]) Send(update StateUpdate[S]) bool

Send queues a state update for application on the loop goroutine. It returns false when update is nil, the Effects value has no update channel, or its context has been cancelled before the update could be queued. Send may block while waiting for a receiver; cancellation unblocks it. It is safe to call on a zero Effects value. Call Send from off-loop work; Handle, View, and fold callbacks already run on the loop and must mutate state directly rather than queueing work back to themselves.

func (Effects[S]) SetClipboard

func (fx Effects[S]) SetClipboard(text string)

SetClipboard writes text to the system clipboard: via OSC52 on the next flush in a terminal, directly in a window. Loop-goroutine-only, like Quit. Terminals without OSC52 support ignore it. Safe on a zero Effects value.

func (Effects[S]) Suspend

func (fx Effects[S]) Suspend()

Suspend releases the terminal (cooked mode, main screen, cursor visible), suspends the process like the shell's Ctrl-Z would (SIGTSTP to the process group), and on resume (fg/SIGCONT) restores the terminal and repaints. On platforms without job control it is a release/restore round trip. The framework never binds a key to this — apps decide what (if anything) triggers it. Loop-goroutine-only, like Quit. No-op on window and browser hosts and on a zero Effects value.

type Event

type Event interface {
	// contains filtered or unexported methods
}

Event is the closed set of host inputs the loop delivers to Handle: terminal input, resizes, and the solved layout of a Root frame. It is sealed: the framework defines every implementation, apps only consume them with a type switch. This is not TEA — events are host inputs, never app-defined messages; async results remain StateUpdates.

type FileSelection

type FileSelection struct {
	Path string
	Err  error
}

FileSelection is the result of a terminal-delegated file picker.

type FocusEvent

type FocusEvent struct{ Focused bool }

FocusEvent reports terminal focus changes (see WithReportFocus).

type Frame

type Frame struct {
	// Content is the styled frame text. It is ignored when Root is set.
	Content string
	// Cursor places the hardware cursor, in frame cell coordinates
	// ((0,0) is the frame's top-left). nil hides the cursor — unless Root
	// holds a focused layout.Input, whose caret then places it.
	Cursor *Cursor
	// CursorStyle styles the cursor a focused layout.Input's caret places
	// (when Cursor is nil); nil is the terminal's default.
	CursorStyle *CursorStyle
	// Title sets the terminal window title when non-empty. It is emitted
	// only when it changes, and reset on exit if it was ever set.
	Title string
	// CellImages draws images as half-block cells even in a terminal that
	// shows pictures (and icon buttons as their glyphs): for an app that
	// lets its user turn pictures off.
	CellImages bool
	// Root, when set, is the frame's layout tree. The host solves and paints
	// it at the frame size, so View needs no Solve call or size bookkeeping,
	// and MouseEvent.Target names the ID'd node under the pointer. Frames
	// whose Root holds a container (Row, Col) are not comparable with ==.
	Root layout.Node
}

Frame is what View returns: rendered content plus terminal metadata. The zero value is a blank frame with no cursor and no title.

func ComposeFrame added in v0.2.0

func ComposeFrame(frame Frame, width, height int) (Frame, layout.Composition)

ComposeFrame resolves frame.Root, when set, into frame.Content at width×height and returns the composition for hit-testing. A nil Cursor is placed at the caret of the topmost focused layout.Input, if any. A frame without Root is returned unchanged with an empty composition. Run calls it before every draw; test harnesses call it to render exactly as Run does.

type Host added in v0.2.0

type Host interface {
	Run(context.Context, *Session) error
}

Host runs an App through a platform-specific driver selected by Run.

type HostServices added in v0.2.0

type HostServices struct {
	Capabilities  Capabilities
	SetClipboard  func(string)
	ReadClipboard func()
	ShowDialog    func(Dialog, func(DialogResult))
	Notify        func(Notification)
	Desktop       func(DesktopCommand)
	// CellSurface enables the shared cell input, layout, dialog, menu, and
	// secondary-window rules. Graphical hosts leave it false.
	CellSurface bool
	// PublishMedia receives the app's current media snapshot after a painted
	// frame. A nil snapshot clears the host's published item.
	PublishMedia func(*NowPlaying)
}

HostServices installs optional capabilities and services before a Session's first step. Apps use Effects for these operations.

type HostState added in v0.2.0

type HostState struct {
	Capabilities Capabilities
	Menus        []Menu
	Windows      []Window
	NowPlaying   *NowPlaying
}

HostState is a values-only snapshot used to synchronize host presentation after a step. Target-specific lookups are Session methods.

type Key

type Key int
const (
	KeyUnknown Key = iota
	KeyUp
	KeyDown
	KeyEnter
	KeyCtrlC
	KeyBackspace
	KeyCharacter
	KeyTab
	KeyEscape
	KeyLeft
	KeyRight
	KeyDelete
	KeyHome
	KeyEnd
	KeyPageUp
	KeyPageDown
	KeyF1
	KeyF2
	KeyF3
	KeyF4
	KeyF5
	KeyF6
	KeyF7
	KeyF8
	KeyF9
	KeyF10
	KeyF11
	KeyF12
)

type KeyEvent

type KeyEvent struct {
	Key  Key
	Rune rune
	Mod  Mod

	Caret    int
	HasCaret bool
}

KeyEvent is a key press. Rune is set when Key is KeyCharacter.

HasCaret reports that the host placed Caret: for KeyUp and KeyDown while a multi-line layout.Input has focus in a host that lays its text out differently from the app's widget (a window wraps by words in its font), Caret is the byte offset into that Input's Value one visual row up or down, at the column the caret is moving along. Pass it to the widget (flatui.Textarea.MoveTo) instead of its own row move. Terminal hosts leave it unset: the widget's rows are the terminal's.

type LayoutEvent added in v0.2.0

type LayoutEvent struct {
	Rects map[string]layout.Rect
	// PointRects preserves native point geometry before conversion to cells.
	// Window hosts populate it; terminal hosts leave it nil. Like Rects,
	// this is the handler's own copy. Prefer it for native measurements.
	PointRects map[string]layout.PointRect
	// Window is the window the rects are in ("" the main window).
	Window string
}

LayoutEvent reports the solved rect of every ID'd node in a Root frame. The host delivers it before painting whenever those rects differ from the ones it last delivered, so state derived from geometry — a list's visible rows, a pane's width — is adopted before the frame is shown. Handle it like ResizeEvent: copy what you need into state, and the next View sees it. Rects is the handler's own copy.

type MediaCommand added in v0.2.0

type MediaCommand uint8

MediaCommand is a command from the system media controls.

const (
	MediaPlay MediaCommand = iota + 1
	MediaPause
	MediaTogglePlayPause
	MediaNext
	MediaPrevious
)

type MediaEvent added in v0.2.0

type MediaEvent struct{ Command MediaCommand }

MediaEvent delivers a system media command to the app. The app decides what the command means and performs its own playback actions.

type Menu struct {
	Title string
	Items []MenuItem
}

Menu is a titled list of commands in the menu bar (Frame.Menus).

type MenuEvent struct {
	ID     string
	Target string
}

MenuEvent reports a chosen menu item: from the menu bar, a shortcut, or a context menu. Target is the ID of the node whose context menu it came from ("" otherwise).

type MenuItem struct {
	ID                string
	Label             string
	Keys              []KeyEvent
	Checked, Disabled bool
	Separator         bool
	Items             []MenuItem
}

MenuItem is one command of a menu. Choosing it delivers a MenuEvent with its ID. Keys are its shortcuts: a host delivers a key equal to one of them (Key, Rune, and Mod; letters in either case) as the item's MenuEvent instead of a KeyEvent — list several to cover hosts, such as ⌘S for a window and Ctrl+S for a terminal. Most terminals can send only a plain Ctrl+letter: not with Shift, and not Ctrl+I, M, H, or [ (they are Tab, Enter, Backspace, and Esc). A Disabled item is shown dimmed and cannot be chosen; its shortcuts do nothing. Checked shows a check mark. Separator makes the item a divider (its other fields are ignored); Items makes it a submenu.

func MenuShortcut(menus []Menu, key KeyEvent) (MenuItem, bool)

MenuShortcut finds the item whose Keys contain key, searching menus and their submenus in order; ok is false when none does. Hosts route shortcuts with it; it is exported for apps that list their shortcuts.

type Mod

type Mod int

Mod is a bitmask of key modifiers.

const (
	ModShift Mod = 1 << iota
	ModAlt
	ModCtrl
	// ModSuper is the Command key on macOS (the Windows or Super key
	// elsewhere): reported by a window, and by terminals that report it —
	// as Super, or as the xterm encoding's Meta bit (CSI 1;9D for ⌘←).
	ModSuper
)

func (Mod) Contains

func (m Mod) Contains(mods Mod) bool

type MouseAction

type MouseAction int
const (
	MousePress MouseAction = iota
	MouseRelease
	MouseMotion
)

type MouseButton

type MouseButton int
const (
	MouseNone MouseButton = iota
	MouseLeft
	MouseMiddle
	MouseRight
	MouseWheelUp
	MouseWheelDown
	// MouseWheelLeft and MouseWheelRight are horizontal scrolling, as a
	// trackpad's sideways swipe or a tilted wheel reports it.
	MouseWheelLeft
	MouseWheelRight
	// MouseBack and MouseForward are a mouse's side buttons.
	MouseBack
	MouseForward
)

type MouseEvent

type MouseEvent struct {
	X, Y   int
	Button MouseButton
	Action MouseAction
	Mod    Mod
	// Target is the ID of the topmost ID'd layout node under the pointer in
	// the last drawn frame, when that frame set Frame.Root. It is "" for
	// string frames, over an overlay area with no ID'd node, or where no
	// ID'd node is painted.
	Target string
	// TargetRect is the solved rect of Target (zero when Target is ""), so a
	// click can be made node-local with X - TargetRect.X, Y - TargetRect.Y.
	TargetRect layout.Rect
	// HasCaret reports that the pointer is over a layout.Input with an ID
	// (Target) and Caret is the byte offset into its Value nearest the
	// pointer, as the host laid the text out — so a click or drag can place
	// the caret exactly whatever the font. A window keeps reporting carets
	// for the Input a drag began on, clamped to it.
	Caret    int
	HasCaret bool
	// Clicks is the native consecutive click count (2: word, 3: all).
	// Zero means a normal single click, as in terminal events.
	Clicks int
	// Clear is a press on a clearable input's clear affordance. Target
	// remains the input ID; the app applies the edit on its loop.
	Clear bool
	// Window is the window the pointer is in ("" the main window); X, Y,
	// Target, and TargetRect are in its frame.
	Window string
}

MouseEvent is a mouse press/release/motion/wheel; X/Y are zero-based cell coordinates from the top-left of the frame (see WithMouse).

type MouseMode

type MouseMode int

MouseMode selects which mouse events the terminal reports.

const (
	// MouseModeNone reports no mouse events (the default).
	MouseModeNone MouseMode = iota
	// MouseModeCellMotion reports clicks, releases, wheel, and drag motion.
	MouseModeCellMotion
	// MouseModeAllMotion additionally reports motion with no button held.
	MouseModeAllMotion
)

type NoopTracer

type NoopTracer struct{}

func (NoopTracer) Event

func (NoopTracer) Event(Event)

func (NoopTracer) Update

func (NoopTracer) Update(string)

type Notification added in v0.2.0

type Notification struct {
	Title, Body string
}

Notification is a message for the user outside the app's frame: a system notification in a window; in a terminal, the terminal's own notification where it shows them (iTerm2, Ghostty, WezTerm, kitty, foot, and through tmux with allow-passthrough on). Title is its heading and Body its text; either may be empty.

type NowPlaying added in v0.2.0

type NowPlaying struct {
	Title, Artist, Album string
	Duration, Position   time.Duration
	Playing              bool
	CanNext, CanPrevious bool
}

NowPlaying is the app's current media snapshot for native system controls. Position is elapsed playback time; a native host lets the system advance it using Playing while the app is in the background.

type OpenDialog added in v0.2.0

type OpenDialog struct {
	Title     string
	Directory string
	Types     []string
	Multiple  bool
	Folders   bool
}

OpenDialog asks for files (or folders) to open. Directory is where it starts ("" the working directory); Types limits files to these extensions (without dots; nil: any); Multiple allows several; Folders asks for folders instead of files.

type Option

type Option interface {
	ConfigureRun(*RunConfig)
}

Option configures Run behavior. Options are host-plumbing values; the standard With* functions are the application-facing constructors.

func WithInline

func WithInline() Option

WithInline renders below the shell prompt instead of in the alternate screen: the frame occupies exactly its own lines, the terminal's scrollback stays intact, and on exit the final frame remains visible with the prompt landing below it. Mouse reporting cannot be enabled because an inline frame has no stable terminal origin; Run returns ErrInlineMouseUnsupported for that combination.

func WithInput

func WithInput(in io.Reader) Option

WithInput sets the event source. Default: os.Stdin.

func WithMouse

func WithMouse(mode MouseMode) Option

WithMouse enables terminal mouse reporting; events arrive as MouseEvent. MouseModeNone remains compatible with WithInline; reporting modes do not.

func WithOutput

func WithOutput(out io.Writer) Option

WithOutput sets the render sink. Default: os.Stdout.

func WithReportFocus

func WithReportFocus() Option

WithReportFocus enables focus reporting; terminal focus changes arrive as FocusEvent. Some terminals and multiplexers need configuration to report focus (tmux: focus-events).

func WithoutBracketedPaste

func WithoutBracketedPaste() Option

WithoutBracketedPaste disables bracketed paste mode. It is on by default: without it a paste arrives as a flood of individual key events instead of one PasteEvent.

func WithoutDefaultQuit

func WithoutDefaultQuit() Option

WithoutDefaultQuit delivers Ctrl-C to the app instead of exiting the loop. The app must call fx.Quit(), close the input, or cancel the context to exit.

type PasteEvent

type PasteEvent struct{ Text string }

PasteEvent is a bracketed paste (paste mode is on by default; see WithoutBracketedPaste).

type RenderContext

type RenderContext struct {
	Width        int
	Height       int
	ColorProfile colorprofile.Profile
	// Window is the window being drawn: "" for the main window, or a
	// secondary window's ID (App.Windows).
	Window string
	// Graphical reports a host that draws in points — a native window:
	// Points sizes, images, and icon shapes show as themselves. False in a
	// terminal, where they round up to whole cells and show their text, so
	// a view can size generously for one and compactly for the other.
	Graphical    bool
	Capabilities Capabilities
}

type ResizeEvent

type ResizeEvent struct {
	Width  int
	Height int
}

ResizeEvent reports the terminal size in cells. The loop delivers one at startup and, on Unix, one per SIGWINCH. On Windows, ultraviolet can deliver console window-size events when connected to a real console. Sizes fall back to 72×24 when the output is not a terminal.

type RunConfig added in v0.2.0

type RunConfig struct {
	// contains filtered or unexported fields
}

RunConfig is opaque Run configuration supplied to Option implementations. Its exported methods are for host plumbing; apps should use With* options.

func (*RunConfig) UseFallbackHost added in v0.2.0

func (c *RunConfig) UseFallbackHost(host Host)

UseFallbackHost selects a host only when no ordinary host option selects one. Repeating the same optional host is harmless; ordinary hosts still conflict with one another through UseHost.

func (*RunConfig) UseHost added in v0.2.0

func (c *RunConfig) UseHost(host Host)

UseHost selects a host driver for Run. Supplying multiple host-installing options makes Run return ErrMultipleHosts.

type SaveDialog added in v0.2.0

type SaveDialog struct {
	Title     string
	Directory string
	Name      string
	Types     []string
}

SaveDialog asks where to save. Directory is where it starts; Name is the proposed file name; Types limits the extensions offered.

type Scope

type Scope struct {
	// contains filtered or unexported fields
}

Scope groups async work under a shared cancellable context. Cancel() cancels all in-flight work started through the scope's Go, Stream, and Every helpers. This closes the "Every/Stream can't be cancelled by name" gap that the flat-docker dogfood found (Task 4 — Logs streaming needed a 30-line hand-rolled goroutine because flatte.Stream runs for the app's entire loop lifetime).

Usage:

scope := flatte.NewScope(fx, "logs")
flatte.ScopeStream(scope, fx, func(ctx context.Context, send func(string)) { ... }, fold)
// On selection change or screen leave:
scope.Cancel()
scope = flatte.NewScope(fx, "logs")  // fresh scope for new selection

func NewScope

func NewScope[S any](fx Effects[S], name string) *Scope

NewScope creates a scope whose context is derived from fx.Ctx(). The name prefixes the Named updates produced by the scope's helpers.

func (*Scope) Cancel

func (s *Scope) Cancel()

Cancel cancels all in-flight work started through this scope. The scope's context is cancelled, which causes every goroutine spawned by ScopeGo/ScopeStream/ScopeEvery to see ctx.Done() and exit. Updates that were already queued but have not been applied are discarded as well.

func (*Scope) Ctx

func (s *Scope) Ctx() context.Context

Ctx returns the scope's cancellable context. Use this to derive further child contexts if needed.

type Session added in v0.2.0

type Session struct {
	// contains filtered or unexported fields
}

Session is the non-generic, minimal host driver handle for one App[S]. Application state and generic Effects remain private to this package.

func NewSession added in v0.2.0

func NewSession[S any](ctx context.Context, app App[S]) *Session

NewSession wraps an app for an offscreen host. Run constructs sessions itself for hosts selected through an Option.

func (*Session) Cancel added in v0.2.0

func (s *Session) Cancel()

Cancel stops Effects work without calling the app's OnExit hook.

func (*Session) ContextMenu added in v0.2.0

func (s *Session) ContextMenu(target string) []MenuItem

ContextMenu returns the current menu items for a target ID.

func (*Session) State added in v0.2.0

func (s *Session) State() HostState

func (*Session) Step added in v0.2.0

func (s *Session) Step(input StepInput) StepResult

Step advances the shared host loop without blocking. Host drivers own their wait mechanism (channels, callbacks, or animation frames) and pass its result here. Events and queued updates are processed before a requested frame.

func (*Session) Updates added in v0.2.0

func (s *Session) Updates() <-chan struct{}

Updates returns a coalesced notification channel. Hosts select on it and

func (*Session) UseHostServices added in v0.2.0

func (s *Session) UseHostServices(services HostServices)

UseHostServices installs a host's capabilities and optional services. Call it before the first StepInput.Start.

func (*Session) UsesNowPlaying added in v0.2.0

func (s *Session) UsesNowPlaying() bool

UsesNowPlaying reports whether the app supplies a NowPlaying callback.

func (*Session) WindowFrame added in v0.2.0

func (s *Session) WindowFrame(id string) (Frame, bool)

WindowFrame returns the latest cell-host frame for a secondary window.

type StateUpdate

type StateUpdate[S any] interface {
	Apply(*S)
	Name() string
}

func Named

func Named[S any](name string, apply func(*S)) StateUpdate[S]

type StepInput added in v0.2.0

type StepInput struct {
	Events         []Event
	Resize         *ResizeEvent
	Start          *ResizeEvent
	UpdatesPending bool
	FrameDue       bool
	Quit           bool
	RenderContext  RenderContext
}

StepInput is one non-blocking turn of the shared host loop. A driver passes the events it received, whether async updates are pending, a frame deadline, and context cancellation as inputs; it never waits inside Step.

type StepResult added in v0.2.0

type StepResult struct {
	Frame Frame
	Paint bool
	Dirty bool
	Quit  bool
}

StepResult reports whether the driver should paint, the cell frame prepared by a cell host, and whether the loop should stop.

type Tracer

type Tracer interface {
	Event(Event)
	Update(string)
}

type UpdateTracer

type UpdateTracer func(string)

func (UpdateTracer) Event

func (UpdateTracer) Event(Event)

func (UpdateTracer) Update

func (f UpdateTracer) Update(name string)

type Window added in v0.2.0

type Window struct {
	ID                  string
	Width, Height       int
	MinWidth, MinHeight int
	Autosave            string
}

Window is a secondary window an app declares (App.Windows). ID names it: View draws it when RenderContext.Window is ID, and its events carry it. Width and Height are its initial content size in cells (0: 60×20); MinWidth and MinHeight its smallest. Autosave, when set, names the window's saved frame: a desktop host restores its position and size from it. A terminal draws a window over the main frame instead.

type WindowEvent added in v0.2.0

type WindowEvent struct {
	Window string
	Kind   WindowEventKind
}

WindowEvent reports a window gaining focus or the user asking to close it.

type WindowEventKind added in v0.2.0

type WindowEventKind int

WindowEventKind is what a WindowEvent reports.

const (
	// WindowFocused: Window ("" the main window) now has the keyboard; keys
	// and pastes go to it until the next WindowFocused.
	WindowFocused WindowEventKind = iota
	// WindowCloseRequest: the user asked to close Window (its close button,
	// ⌘W). It closes when the app stops declaring it — or stays, if the app
	// keeps it (to ask about unsaved changes, say).
	WindowCloseRequest
)

Directories

Path Synopsis
Package flatest is a deterministic, synchronous test harness for flat apps: it drives an App through scripted events and controlled time, exercising real async folds without goroutine races, real clocks, or a terminal.
Package flatest is a deterministic, synchronous test harness for flat apps: it drives an App through scripted events and controlled time, exercising real async folds without goroutine races, real clocks, or a terminal.
internal/textedit
Package textedit lays out editable text in terminal cells: soft wrapping by grapheme clusters, horizontal windows, selection runs, and the scroll that keeps a cursor visible.
Package textedit lays out editable text in terminal cells: soft wrapping by grapheme clusters, horizontal windows, selection runs, and the scroll that keeps a cursor visible.
layout
Package layout is a flexbox-style layout and composition engine for Flatte.
Package layout is a flexbox-style layout and composition engine for Flatte.
internal
hostconformance
Package hostconformance contains one application scenario shared by the terminal, browser, and window host conformance tests.
Package hostconformance contains one application scenario shared by the terminal, browser, and window host conformance tests.
sessionaccess
Package sessionaccess bridges root runtime details to packages inside the module.
Package sessionaccess bridges root runtime details to packages inside the module.
testkit
Package testkit contains Effects and Session construction helpers for Flatte's in-repository harnesses and samples.
Package testkit contains Effects and Session construction helpers for Flatte's in-repository harnesses and samples.
window module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL