kite

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 5 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

🪁 Kite

Docs & Live Demos · Go Reference · CI · MIT License · Go 1.26.1+

Kite is a modern, DOM-like terminal UI framework for Go. It brings web-inspired development paradigms—such as a logical DOM tree, CSS-style flexbox layout, standard event propagation, and scrolling—to the terminal environment.

kitex_demo

✨ Features

  • Lay out text, buttons, inputs, and tables in terminal cells with Flexbox or Grid. Style interactive states such as :hover and :focus separately, and respond to the host’s preferred color scheme.
  • Handle keyboard and mouse input through capture, target, and bubble phases. Focus navigation, scrolling, and text editing work on the same DOM tree.
  • Run an interactive editor, pager, or shell with ExecProcess, then resume the TUI.
  • Update individual nodes directly or describe the UI as a function of state with Kitex. Both use the same rendering pipeline and headless test backend. A Kitex error boundary can replace a failed subtree without interrupting its siblings.

The documentation site pairs Go snippets with four interactive browser demos, and the Learn Kite guide adds six live Task Manager examples. See Preview the documentation to run the site locally.

Choosing Your Layer

What are you building? Start here
Full-screen reactive app kite + backend/uv + extras/kitex. Mount components with kitex.CreateRoot(app). See Kitex hooks for lazy state, context, and keyboard shortcuts.
SSH or custom PTY app Use backend/uv with session streams and resize notifications.
Browser canvas app Build for GOOS=js GOARCH=wasm and pass wasm.New(canvas) to kite.New. The same Kite elements and Kitex components run on the canvas.
Inline CLI with permanent scrollback extras/trail + extras/kitex. Use <Static> for finished items and keep the current task live below them.
Retained-mode DOM or custom widgets kite + backend/uv + element + style. Use dom for node identity and traversal, event for input.
Optional app features extras/kites for global state, extras/wind for async queries with prefetching, polling, and retries, streams, and optimistic mutations, extras/flight for stack routing, extras/form for typed validation, in-place reset, and cancellable async submission.
Optional tools and integrations extras/stage for a component playground, extras/clipboard for the OS-native multi-MIME clipboard, devtools for the web inspector, X-Ray, and profiler, testenv and extras/kitex/kitextest for headless and golden tests.

🚀 Getting Started

With Go 1.26.1 or newer, start in an empty directory:

go mod init hello-kite
go get github.com/masterkeysrd/kite

Save either example below as main.go, then run go mod tidy and go run . in your terminal. Hover over the button to highlight it, click to increment the count, and press Ctrl+C to quit.

Reactive component app

Kitex calls App again when the count changes. The root mounts a full-viewport container and unmounts the component tree when the engine stops.

package main

import (
	"context"
	"log"

	"github.com/masterkeysrd/kite"
	"github.com/masterkeysrd/kite/backend/uv"
	"github.com/masterkeysrd/kite/event"
	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/style"
)

var App = kitex.FC("App", func(_ kitex.NoProps) kitex.Node {
	count, setCount := kitex.UseState(0)
	hover := style.S().Background(style.Hex("#334155"))

	return kitex.Button(kitex.ButtonProps{
		Style: style.S().Hover(hover),
		OnPress: func() {
			setCount(count() + 1)
		},
	}, kitex.Textf("Count: %d", count()))
})

func main() {
	b, err := uv.New()
	if err != nil {
		log.Fatal(err)
	}

	app := kite.New(b, kite.WithMouseMode(kite.MouseModeTrack))
	root := kitex.CreateRoot(app)
	root.Render(App())

	app.Document().AddEventListener(event.EventKeyDown, func(e event.Event) {
		if k, ok := e.(*event.KeyEvent); ok && k.MatchString("ctrl+c") {
			app.Stop()
		}
	}, event.Capture())

	if err := app.Run(context.Background()); err != nil {
		log.Fatal(err)
	}
}
Low-level retained DOM

Here the button is created once. Its press handler updates the existing label rather than rendering a component again.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/masterkeysrd/kite"
	"github.com/masterkeysrd/kite/backend/uv"
	"github.com/masterkeysrd/kite/element"
	"github.com/masterkeysrd/kite/event"
	"github.com/masterkeysrd/kite/style"
)

func main() {
	b, err := uv.New()
	if err != nil {
		log.Fatal(err)
	}

	app := kite.New(b, kite.WithMouseMode(kite.MouseModeTrack))
	count := 0
	hover := style.S().Background(style.Hex("#334155"))
	button := element.Button("Count: 0").Style(style.S().Hover(hover))
	button.OnPress(func() {
		count++
		button.SetData(fmt.Sprintf("Count: %d", count))
	})

	ui := element.Box(button)
	app.Mount(ui)
	app.Document().AddEventListener(event.EventKeyDown, func(e event.Event) {
		if k, ok := e.(*event.KeyEvent); ok && k.MatchString("ctrl+c") {
			app.Stop()
		}
	}, event.Capture())

	if err := app.Run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

🏗 Architecture Overview

Public packages are the interfaces to build against:

Concern Packages
Application lifecycle and terminal I/O kite creates and configures the app; engine runs frames and schedules work; backend supplies input and receives frames; terminal exposes host services such as the cursor and clipboard.
UI and interaction dom defines the tree; element supplies widgets, including clickable labels for form controls; style describes appearance and layout; event defines input and propagation.
Supporting tools animation interpolates properties; promise represents async results; log supports TUI-safe logging; testenv runs headless tests; devtools inspects a running app.

Internal pipeline packages are implementation details, not application imports. Each frame, internal/render bridges the DOM to visual objects, internal/styler resolves the style cascade, internal/layout computes geometry, and internal/paint draws cells for the backend. internal/focus handles focus navigation; internal/text provides the editing buffer.

🧪 Headless Testing

Save this as input_test.go alongside either quickstart. Flush paints the pending frame. The first run creates testdata/input.golden; review and commit it so subsequent runs compare against a known frame.

package main

import (
	"testing"

	"github.com/masterkeysrd/kite/element"
	"github.com/masterkeysrd/kite/testenv"
)

func TestInput(t *testing.T) {
	env := testenv.New(t, 32, 4)
	env.Mount(element.Input("").WithID("name"))
	env.Flush()

	input := testenv.ByID[*element.InputElement](t, env, "name")
	input.Focus()
	env.Type("Kite")
	env.Flush()

	if got := input.Value(); got != "Kite" {
		t.Fatalf("input value = %q, want Kite", got)
	}
	env.MatchGolden(t, "input")
}

🛠 Developer Tools

Call this helper before app.Run in a development build and handle the returned error. F12 opens the Web Inspector for the DOM tree, computed styles, and frame profiler. Ctrl+D toggles X-Ray Mode to show layout boxes in the terminal.

package main

import (
	"github.com/masterkeysrd/kite"
	"github.com/masterkeysrd/kite/devtools"
)

func installTools(app *kite.Engine) error {
	_, err := devtools.Install(app, devtools.Options{
		ServerAddr: "127.0.0.1:8080",
	})
	return err
}

🎭 Stage – Component Playground

Preview a component without starting the rest of your application. Change the label in the controls panel, then press the button to see its action in the log. See the Stage demo for more scenes.

stage

package main

import (
	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/extras/stage"
)

func main() {
	playground := stage.New()
	playground.Register("Button", []stage.Scene{
		{
			Name: "Default",
			Render: func(c *stage.Context) kitex.Node {
				label := c.Text("Label", "Save")
				return kitex.Button(kitex.ButtonProps{
					OnPress: func() {
						c.Log("Save pressed")
					},
				}, kitex.Text(label))
			},
		},
	})
	playground.Run()
}

👣 Trail – Inline CLI Mode

Trail runs at the terminal cursor without switching to the alternate screen. trail.Static writes new items permanently to scrollback; the live UI below can change without rewriting them. Trail handles Ctrl+C by default. See the Trail demo for a multi-step task list.

trail_demo

package main

import (
	"context"
	"log"

	"github.com/masterkeysrd/kite/extras/kitex"
	"github.com/masterkeysrd/kite/extras/trail"
)

var App = kitex.FC("App", func(_ kitex.NoProps) kitex.Node {
	return kitex.Fragment(
		trail.Static([]string{"Configuration loaded"}, func(item string, _ int) kitex.Node {
			return kitex.Text(item)
		}),
		kitex.Text("Ready. Press Ctrl+C to quit."),
	)
})

func main() {
	if err := trail.Run(context.Background(), App()); err != nil {
		log.Fatal(err)
	}
}

📋 Multi-MIME Clipboard

The default terminal clipboard uses OSC 52 for plain text. For local apps that accept images, HTML, or URI lists, configure the native provider when creating the engine. Widgets access it through their document's terminal:

package main

import (
	"github.com/masterkeysrd/kite"
	"github.com/masterkeysrd/kite/dom"
	"github.com/masterkeysrd/kite/extras/clipboard"
	"github.com/masterkeysrd/kite/promise"
)

func newApp(b kite.Backend) *kite.Engine {
	return kite.New(b, kite.WithClipboard(clipboard.New()))
}

func readPNG(doc dom.Document) *promise.Promise[[]byte] {
	return doc.Terminal().Clipboard().Read("image/png")
}

In a paste listener, event.ClipboardEvent.Items contains the available MIME payloads. Call PreventDefault() when you handle an image yourself; otherwise a focused text control inserts the plain-text payload.

✨ Animations & CSS Grid Layout

Grid supports explicit tracks, fr units, and auto-placement. Use el.Animate(from, to, animation.Options{Duration: time.Second}) for grid tracks, dimensions, and colors, or animation.Play(win, tween) for custom values. Register entrance animations with el.OnConnect(replay) and cleanup with el.OnDisconnect(cleanup).

grid_animation

⚡ Performance & Benchmarks

BenchmarkEngine_RealisticApp_1000Nodes mounts a header, sidebar, and scrollable content area with over 1,200 nested nodes. Each iteration changes a text node and runs a frame through sync, style, layout, and paint.

Results (Tested on Apple M5 Max)
Benchmark Latency / Frame Frame Rate (FPS) Memory / Frame Allocations / Frame
Realistic App (1,200+ Nodes) ~0.47 ms ~2,110 FPS 0.97 MB 7,117

Frame rate here is benchmark throughput, not a terminal refresh rate. To run it yourself:

go test -timeout 30s -bench=BenchmarkEngine_RealisticApp -benchmem ./engine

📖 Documentation & Guides

🤝 Contributing

Start with the contributing guide for setup, tests, and pull requests. Our code of conduct sets expectations for working together. To report a security concern privately, follow the security policy.

📄 License

Kite is released under the MIT License. Kite source files do not require individual copyright headers. Preserve existing copyright and license notices in third-party code.

Documentation

Overview

Package kite builds terminal user interfaces around a logical DOM. Input events travel through that tree in capture, target, and bubble phases. Each frame, the engine resolves styles, lays out elements in terminal cells, and paints the result to the application's chosen backend.

For example, to run a mounted element with the backend/uv terminal backend:

func run(ctx context.Context, root dom.Element) error {
	b, err := uv.New()
	if err != nil {
		return err
	}

	app := kite.New(b, kite.WithMouseMode(kite.MouseModeTrack))
	app.Mount(root)

	return app.Run(ctx)
}

Applications choose their own exit keys or cancel the context to stop Run. Use element and style to build the interface, event to handle input, and dom to navigate the document. The engine, backend, and terminal packages expose the runtime and its host interfaces; testenv runs it without a physical TTY.

Optional packages include extras/kitex for reactive components, extras/trail for inline CLIs, extras/kites for shared state, extras/wind for async data, extras/flight for navigation, extras/form for forms, extras/stage for component previews, extras/clipboard for native clipboard access, and devtools for inspection.

Example
package main

import (
	"fmt"

	"github.com/masterkeysrd/kite"
	"github.com/masterkeysrd/kite/backend/mock"
	"github.com/masterkeysrd/kite/element"
)

func main() {
	b := mock.New(5, 1)
	app := kite.New(b, kite.WithMouseMode(kite.MouseModeClick))
	defer app.Stop()

	app.Mount(element.Box("Ready"))
	app.Frame()

	screen := b.LastFrame().Surface
	for x := range screen.Bounds().Size.Width {
		fmt.Print(screen.CellAt(x, 0).Content)
	}
	fmt.Println()
}
Output:
Ready

Index

Examples

Constants

View Source
const (
	// MouseModeOff disables mouse reporting.
	MouseModeOff = engine.MouseModeOff
	// MouseModeClick reports clicks only.
	MouseModeClick = engine.MouseModeClick
	// MouseModeDrag reports clicks and motion while a button is held (default).
	MouseModeDrag = engine.MouseModeDrag
	// MouseModeTrack reports all mouse motion, including hover.
	MouseModeTrack = engine.MouseModeTrack
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Backend

type Backend = backend.Backend

Backend supplies terminal input and receives rendered frames.

type Clipboard

type Clipboard = terminal.Clipboard

Clipboard provides asynchronous access to text and MIME-typed data.

type Clock

type Clock = engine.Clock

Clock supplies time for frame scheduling.

func RealClock

func RealClock() Clock

RealClock returns a clock backed by the standard library.

type Document

type Document = dom.Document

Document is the root of the logical DOM tree.

type Engine

type Engine = engine.Engine

Engine runs the event loop and renders the mounted document.

func New

func New(b Backend, opts ...Option) *Engine

New constructs an engine for b. Options apply in order; nil options are ignored.

type MouseMode

type MouseMode = engine.MouseMode

MouseMode selects the level of mouse reporting.

type Option

type Option func(*config)

Option configures an engine before it starts.

func WithClipboard

func WithClipboard(cb Clipboard) Option

WithClipboard selects the clipboard provider used by the document.

func WithClock

func WithClock(clk Clock) Option

WithClock selects the time source for frame scheduling.

func WithInline

func WithInline(enabled bool) Option

WithInline selects inline rendering instead of the alternate screen.

func WithMouseMode

func WithMouseMode(mode MouseMode) Option

WithMouseMode selects which mouse events the terminal reports.

func WithOptions

func WithOptions(opts Options) Option

WithOptions replaces the engine options without changing the mouse mode. Pass it first to use opts as a base for subsequent options.

func WithProfiler

func WithProfiler(enabled bool) Option

WithProfiler enables or disables frame profiling at startup.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout sets the shutdown timeout for pending work.

func WithWorkers

func WithWorkers(n int) Option

WithWorkers sets the size of the background worker pool.

type Options

type Options = engine.Options

Options holds the underlying engine configuration.

type Terminal

type Terminal = terminal.Terminal

Terminal exposes host services to a document.

type Timer

type Timer = engine.Timer

Timer is a scheduled engine timer.

Directories

Path Synopsis
Package animation interpolates styles and custom values on the host frame clock.
Package animation interpolates styles and custom values on the host frame clock.
Package backend defines Kite's interface to a terminal or other output device.
Package backend defines Kite's interface to a terminal or other output device.
mock
Package mock provides a headless Kite backend that records frames and accepts synthetic input so tests can exercise a UI without a terminal.
Package mock provides a headless Kite backend that records frames and accepts synthetic input so tests can exercise a UI without a terminal.
uv
Package uv implements Kite's terminal backend using Ultraviolet to render frames and receive input from a terminal.
Package uv implements Kite's terminal backend using Ultraviolet to render frames and receive input from a terminal.
wasm
Package wasm embeds Kite and Kitex applications in an HTML canvas.
Package wasm embeds Kite and Kitex applications in an HTML canvas.
Package cursor translates between text offsets and terminal cells.
Package cursor translates between text offsets and terminal cells.
Package devtools provides standard developer tools for Kite applications, including an X-Ray mode for visual debugging and a web-based DOM inspector.
Package devtools provides standard developer tools for Kite applications, including an X-Ray mode for visual debugging and a web-based DOM inspector.
inspector
Package inspector captures snapshots of a running Kite application's DOM, layout fragments, and element styles for the DevTools inspector.
Package inspector captures snapshots of a running Kite application's DOM, layout fragments, and element styles for the DevTools inspector.
Package dom defines the interfaces for Kite's logical document tree.
Package dom defines the interfaces for Kite's logical document tree.
Package element provides containers, text, form controls, and overlays for building a Kite document.
Package element provides containers, text, form controls, and overlays for building a Kite document.
Package engine runs Kite applications.
Package engine runs Kite applications.
Package event defines Kite's UI events and listener interfaces.
Package event defines Kite's UI events and listener interfaces.
examples
animation command
app1 command
button command
checkbox_radio command
clipboard command
demoutil
Package demoutil provides logging setup, exit-key bindings and shortcut bars for Kite examples.
Package demoutil provides logging setup, exit-key bindings and shortcut bars for Kite examples.
dialog command
flex command
flight_demo command
form_demo command
grid command
grid_animation command
input command
kites_demo command
kitex_demo command
kitex_hooks command
kitex_ref_demo command
list command
opacity command
overlay command
overlay_tweaks command
reducer command
responsive command
select command
stage command
table command
textarea command
trail_demo command
wind_demo command
extras
clipboard
Package clipboard provides a native clipboard for local Kite applications that need MIME formats beyond plain text.
Package clipboard provides a native clipboard for local Kite applications that need MIME formats beyond plain text.
flight
Package flight implements a stack-based navigation system for Kitex applications.
Package flight implements a stack-based navigation system for Kitex applications.
form
Package form provides a high-level form state and validation engine for Kite applications.
Package form provides a high-level form state and validation engine for Kite applications.
kites
Package kites implements a lightweight, thread-safe external state store (similar to Zustand or Redux) for global state management outside of the VDOM tree.
Package kites implements a lightweight, thread-safe external state store (similar to Zustand or Redux) for global state management outside of the VDOM tree.
kites/kitesdt
Package kitesdt provides the DevTools integration bridge and time-travel debugger mini-plugin for kites global state stores.
Package kitesdt provides the DevTools integration bridge and time-travel debugger mini-plugin for kites global state stores.
kitex
Package kitex builds declarative Kite UIs from typed components and element constructors.
Package kitex builds declarative Kite UIs from typed components and element constructors.
kitex/kitexdt
Package kitexdt provides the DevTools integration bridge for kitex Virtual DOM.
Package kitexdt provides the DevTools integration bridge for kitex Virtual DOM.
kitex/kitextest
Package kitextest provides a lightweight, React-Testing-Library-inspired test harness for rendering, querying, interacting with, and asserting on kitex VDOM components in a headless testenv environment.
Package kitextest provides a lightweight, React-Testing-Library-inspired test harness for rendering, querying, interacting with, and asserting on kitex VDOM components in a headless testenv environment.
stage
Package stage provides an interactive, isolated component development stage and playground for kitex applications.
Package stage provides an interactive, isolated component development stage and playground for kitex applications.
trail
Package trail runs Kitex components inline in the terminal without switching to an alternate screen.
Package trail runs Kitex components inline in the terminal without switching to an alternate screen.
wind
Package wind implements an asynchronous data fetching and caching library for Kitex applications, inspired by React Query.
Package wind implements an asynchronous data fetching and caching library for Kitex applications, inspired by React Query.
wind/winddt
Package winddt provides the DevTools integration bridge for wind async queries and streams.
Package winddt provides the DevTools integration bridge for wind async queries and streams.
Package geom defines the geometric value types used throughout the Kite layout engine.
Package geom defines the geometric value types used throughout the Kite layout engine.
internal
collections
Package collections provides order-preserving slice deletion for Kite internals.
Package collections provides order-preserving slice deletion for Kite internals.
dom
Package dom implements Kite's public DOM interfaces.
Package dom implements Kite's public DOM interfaces.
event
Package event dispatches events through the capture, target, and bubble phases and synthesizes UI events from raw backend input.
Package event dispatches events through the capture, target, and bubble phases and synthesizes UI events from raw backend input.
focus
Package focus implements focus management for Kite.
Package focus implements focus management for Kite.
focus/spatial
Package spatial ranks focusable elements by their position within the active focus scope.
Package spatial ranks focusable elements by their position within the active focus scope.
layout
Package layout computes a fragment tree from render nodes, computed styles, and available space.
Package layout computes a fragment tree from render nodes, computed styles, and available space.
layout/text
Package text shapes strings into grapheme clusters with terminal-cell widths and line-break opportunities for inline layout.
Package text shapes strings into grapheme clusters with terminal-cell widths and line-break opportunities for inline layout.
paint
Package paint implements the paint phase of the Kite rendering pipeline.
Package paint implements the paint phase of the Kite rendering pipeline.
render
Package render provides the core engine for maintaining the render tree.
Package render provides the core engine for maintaining the render tree.
styler
Package styler implements the Kite style resolution engine.
Package styler implements the Kite style resolution engine.
text
Package text provides the Unicode-aware gap buffer used by Kite's text controls for editing and caret movement.
Package text provides the Unicode-aware gap buffer used by Kite's text controls for editing and caret movement.
Package key defines the key event types and modifier constants used by the Kite terminal UI engine.
Package key defines the key event types and modifier constants used by the Kite terminal UI engine.
Package log provides structured logging for Kite without writing over the terminal UI.
Package log provides structured logging for Kite without writing over the terminal UI.
Package promise provides a lightweight, generic Promise<T> implementation for asynchronous operations in the Kite terminal UI engine.
Package promise provides a lightweight, generic Promise<T> implementation for asynchronous operations in the Kite terminal UI engine.
Package style defines layout and appearance properties for Kite elements.
Package style defines layout and appearance properties for Kite elements.
Package terminal defines the host environment context exposed by a Kite document.
Package terminal defines the host environment context exposed by a Kite document.
Package testenv provides an ergonomic testing environment for Kite components.
Package testenv provides an ergonomic testing environment for Kite components.
Package trace provides Chrome Trace Event format instrumentation for the Kite engine.
Package trace provides Chrome Trace Event format instrumentation for the Kite engine.

Jump to

Keyboard shortcuts

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