Documentation
¶
Index ¶
- Variables
- func Alert[S any](fx Effects[S], name string, d AlertDialog, ...)
- func ApplyUpdate[S any](s *S, tracer Tracer, update StateUpdate[S])
- func Cancel[S any](fx Effects[S], name string)
- func Every[S any](fx Effects[S], name string, interval time.Duration, fold func(*S, time.Time)) error
- func Exec[S any](fx Effects[S], name string, cmd *exec.Cmd, fold func(*S, error))
- func Go[S, T any](fx Effects[S], name string, work func(context.Context) (T, error), ...)
- func Latest[S, T any](fx Effects[S], name string, work func(context.Context) (T, error), ...)
- func LoadState[S any](path string, defaultState S) S
- func LoadStateWithError[S any](path string, defaultState S) (S, error)
- func OpenFile[S any](fx Effects[S], name string, d OpenDialog, ...)
- func Run[S any](ctx context.Context, app App[S], opts ...Option) (runErr error)
- func SaveFile[S any](fx Effects[S], name string, d SaveDialog, ...)
- func SaveState[S any](path string, state S) error
- func ScopeEvery[S any](scope *Scope, fx Effects[S], interval time.Duration, fold func(*S, time.Time)) error
- func ScopeGo[S, T any](scope *Scope, fx Effects[S], work func(context.Context) (T, error), ...)
- func ScopeStream[S, T any](scope *Scope, fx Effects[S], source func(context.Context, func(T)), ...)
- func SelectFile[S any](fx Effects[S], name string, cmd *exec.Cmd, fold func(*S, FileSelection))
- func Stream[S, T any](fx Effects[S], name string, source func(context.Context, func(T)), ...)
- type AlertDialog
- type App
- type Capabilities
- type ClipboardEvent
- type Clock
- type Cursor
- type CursorShape
- type CursorStyle
- type Desktop
- type DesktopCommand
- type DesktopEvent
- type Dialog
- type DialogResult
- type DropEvent
- type Effects
- func (fx Effects[S]) Capabilities() Capabilities
- func (fx Effects[S]) Ctx() context.Context
- func (fx Effects[S]) Desktop(command DesktopCommand)
- func (fx Effects[S]) Notify(n Notification)
- func (fx Effects[S]) Print(s string)
- func (fx Effects[S]) Printf(format string, args ...any)
- func (fx Effects[S]) Quit()
- func (fx Effects[S]) ReadClipboard()
- func (fx Effects[S]) Send(update StateUpdate[S]) bool
- func (fx Effects[S]) SetClipboard(text string)
- func (fx Effects[S]) Suspend()
- type Event
- type FileSelection
- type FocusEvent
- type Frame
- type Host
- type HostServices
- type HostState
- type Key
- type KeyEvent
- type LayoutEvent
- type MediaCommand
- type MediaEvent
- type Menu
- type MenuEvent
- type MenuItem
- type Mod
- type MouseAction
- type MouseButton
- type MouseEvent
- type MouseMode
- type NoopTracer
- type Notification
- type NowPlaying
- type OpenDialog
- type Option
- type PasteEvent
- type RenderContext
- type ResizeEvent
- type RunConfig
- type SaveDialog
- type Scope
- type Session
- func (s *Session) Cancel()
- func (s *Session) ContextMenu(target string) []MenuItem
- func (s *Session) State() HostState
- func (s *Session) Step(input StepInput) StepResult
- func (s *Session) Updates() <-chan struct{}
- func (s *Session) UseHostServices(services HostServices)
- func (s *Session) UsesNowPlaying() bool
- func (s *Session) WindowFrame(id string) (Frame, bool)
- type StateUpdate
- type StepInput
- type StepResult
- type Tracer
- type UpdateTracer
- type Window
- type WindowEvent
- type WindowEventKind
Constants ¶
This section is empty.
Variables ¶
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.
var ErrInvalidInterval = errors.New("flat: interval must be positive")
ErrInvalidInterval is returned by Every and ScopeEvery when interval is zero or negative.
var ErrMultipleHosts = errors.New("flatte: multiple host options selected")
ErrMultipleHosts reports that more than one host-installing option was supplied to Run.
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).
var ErrNoSelection = errors.New("flat: no file selected")
ErrNoSelection is returned by SelectFile when the selector command exits successfully without printing a selected path.
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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.
Types ¶
type AlertDialog ¶ added in v0.2.0
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
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
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 ¶
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 ¶
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]) 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 ¶
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 ¶
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
// 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 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 KeyEvent ¶
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 MenuEvent ¶ added in v0.2.0
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 ¶ added in v0.2.0
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 ¶ added in v0.2.0
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 MouseAction ¶
type MouseAction int
const ( MousePress MouseAction = iota MouseRelease MouseMotion )
type MouseButton ¶
type MouseButton int
const ( MouseNone MouseButton = iota MouseLeft MouseMiddle MouseRight MouseWheelUp MouseWheelDown )
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 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
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 WithMouse ¶
WithMouse enables terminal mouse reporting; events arrive as MouseEvent. MouseModeNone remains compatible with WithInline; reporting modes do not.
func WithOutput ¶
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 ¶
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
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.
type SaveDialog ¶ added in v0.2.0
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 ¶
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.
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
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
ContextMenu returns the current menu items for a target ID.
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
UsesNowPlaying reports whether the app supplies a NowPlaying callback.
type StateUpdate ¶
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
StepResult reports whether the driver should paint, the cell frame prepared by a cell host, and whether the loop should stop.
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
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 )
Source Files
¶
- async.go
- browser_events.go
- browser_render.go
- clock.go
- desktop.go
- dialog_term.go
- dialogs.go
- effects.go
- events.go
- file_select.go
- flatte.go
- frame.go
- media.go
- menu.go
- notify.go
- resize_unix.go
- run_native.go
- scope.go
- session.go
- session_step.go
- state.go
- state_syncdir_unix.go
- suspend_unix.go
- terminal.go
- trace.go
- translate.go
- windows.go
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
|
