trail

package
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: 17 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

trail

trail is an Ink-like inline CLI framework built on Kite, its rendering engine, and the kitex reactive Virtual DOM framework.

trail_demo

Features

  • Inline Execution: Runs directly in the standard terminal scrollback without taking over the screen or entering an alternate screen buffer (altscreen).
  • Dynamic Content Height: Automatically resizes the active terminal viewport to exactly match the rendered content height.
  • Contiguous Inline Output: Starts at the current terminal cursor and keeps the active frame immediately after Static output. Growth scrolls when needed; shrinking clears the freed rows below the frame instead of introducing gaps above it. The frame is not pinned to the terminal bottom. Clear() repaints from row 0.
  • <Static> Output: Permanently write completed logs, tasks, and items above the active inline frame into the terminal's native scrollback buffer while continuing to update live interactive components below.
  • Ink-Compatible Mental Model: Declarative component tree with lifecycle controls (Render, WaitUntilExit, Rerender, Unmount, Clear), inline hooks (UseApp, UseInput, UseFocus, UseFocusManager, UseStdout, UseStderr), and inline primitives (Static, Newline, Spacer, Transform).
  • Console & Log Interception: Automatically redirect standard log.Default() or slog output (WithInterceptLog, inst.LogWriter()) cleanly into scrollback above the active frame.
  • Full kitex Interoperability: Pair seamlessly with kitex components (FC, FCC, Box, Span, Text, Textf, Fragment), state (UseState + StateSetter.Update, UseReducer), effects (UseEffect, UseLayoutEffect, UseInterval, UseTimeout), and refs (UseRef, CreateRef).

Quick Start

package main

import (
	"context"
	"time"

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

var App = kitex.FC("App", func(_ kitex.NoProps) kitex.Node {
	count, setCount := kitex.UseState(0)
	app := trail.UseApp()

	trail.UseInput(func(input string, k event.KeyEvent) {
		if input == "q" {
			app.Exit(nil)
		}
	})

	kitex.UseInterval(func() {
		setCount.Update(func(n int) int { return n + 1 })
	}, time.Second)

	return kitex.Box.Style(
		style.S().Padding(0, 1),
		kitex.Span.Style(
			style.S().Bold(true),
			kitex.Textf("Counter: %d (press 'q' to exit)", count()),
		),
	)
})

func main() {
	// Start with trail.Render and block on WaitUntilExit (Ink-style)
	inst, err := trail.Render(context.Background(), App())
	if err != nil {
		panic(err)
	}
	if err := inst.WaitUntilExit(); err != nil {
		panic(err)
	}
}

Static Output

Use trail.Static to permanently insert completed items above the active live UI:

func TaskList(tasks []string) kitex.Node {
	return kitex.Fragment(
		trail.Static(tasks, func(task string, index int) kitex.Node {
			return kitex.Box(kitex.BoxProps{},
				kitex.Text("✔ " + task),
			)
		}),
		kitex.Box(kitex.BoxProps{},
			kitex.Text("Working on next task..."),
		),
	)
}

Instance Lifecycle Controls

trail.Render returns an *Instance that gives you full programmatic control over the inline execution lifecycle:

  • inst.WaitUntilExit() error: Blocks until the app exits and returns the recorded exit error.
  • inst.Rerender(newApp kitex.Node): Dynamically updates the root component tree with a new node.
  • inst.Clear() / app.Clear(): Clears the terminal and scrollback, resets the inline origin, and repaints the mounted app from row 0 without resetting component state.
  • inst.Unmount(): Executes all UseEffectCleanup hooks across the component tree and cleanly halts the engine.
  • inst.LogWriter() io.Writer: Returns an io.Writer that formats log messages and inserts them cleanly into scrollback above the live frame.
inst, _ := trail.Render(ctx, App())

// Later: update root component
inst.Rerender(UpdatedApp())

// Clear inline frame
inst.Clear()

// Unmount and exit
inst.Unmount()

Log Interception (WithInterceptLog)

Pass trail.WithInterceptLog(true) to automatically patch the standard Go log.Default() output while the inline application is running. Log calls are routed above the active inline viewport and restored when the application exits:

inst, err := trail.Render(ctx, App(), trail.WithInterceptLog(true))
// log.Println(...) now writes cleanly above the active inline frame!

Hooks & Controls

Keyboard Input (UseInput)
trail.UseInput(func(input string, k event.KeyEvent) {
    if input == "p" {
        togglePause()
    }
}, trail.InputOptions{IsActive: isInputEnabled})
Focus Management (UseFocus, UseFocusManager)
btnRef := kitex.UseRef[dom.Element](nil)
isFocused := trail.UseFocus(btnRef, trail.FocusOptions{AutoFocus: true})

fm := trail.UseFocusManager()
// fm.FocusNext(), fm.FocusPrevious(), fm.Focus("element-id"), fm.Blur()
Stdout & Stderr Routing (UseStdout, UseStderr)
stdout := trail.UseStdout()
stdout.Write("Task completed!")
size := stdout.Size() // current viewport size

stderr := trail.UseStderr()
stderr.Write("Warning: slow connection")
Element Measurement (MeasureElement)
size := trail.MeasureElement(containerRef)
// size.Width, size.Height in terminal cells
Text Line Transformation (Transform)
trail.Transform(func(line string, idx int) string {
    return fmt.Sprintf("[%02d] %s", idx+1, line)
}, multilineText)

Documentation

Overview

Package trail runs Kitex components inline in the terminal without switching to an alternate screen. The live UI grows or shrinks with its content. Use Static or Instance.InsertAbove to leave completed output in scrollback above the live UI.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MeasureElement

func MeasureElement(ref kitex.Ref[dom.Element]) geom.Size

MeasureElement measures the physical dimensions of an element ref in the current layout. If the ref is nil or not yet mounted/measured, it returns geom.Size{}.

func Newline

func Newline(count ...int) kitex.Node

Newline renders n (default 1) line breaks as a box of height n.

func Run

func Run(ctx context.Context, app kitex.Node, opts ...Option) error

Run creates a new Instance and executes its event loop.

func Spacer

func Spacer() kitex.Node

Spacer creates a flexible space component that expands to fill available flex space.

func Static

func Static[T any](items []T, renderItem func(item T, index int) kitex.Node) kitex.Node

Static renders completed items permanently above the active inline frame. Newly appended items are flushed once into terminal scrollback and do not occupy space in the live inline DOM.

func Transform

func Transform(transform func(line string, index int) string, text string) kitex.Node

Transform splits text into lines, applies transform to each line (if non-nil), and returns a Text node containing the joined transformed lines.

func UseFocus

func UseFocus(ref kitex.Ref[dom.Element], opts ...FocusOptions) bool

UseFocus binds a focus listener to a DOM element ref and reports whether it is focused. If AutoFocus is enabled (and active), it automatically focuses the element on mount.

func UseInput

func UseInput(handler func(input string, k event.KeyEvent), opts ...InputOptions)

UseInput registers a keyboard handler for raw or printable key presses. handler is called with the printable character (or empty string for control/navigation keys) and the underlying event.KeyEvent. By default, input handling is active unless explicitly disabled via InputOptions{IsActive: false}.

Types

type AppHandle

type AppHandle interface {
	// Exit terminates the application and records an optional exit error.
	Exit(err error)

	// InsertAbove permanently flushes a rendered node into the terminal scrollback
	// above the active inline frame.
	InsertAbove(node kitex.Node)

	// Println permanently writes a text line into the scrollback above the frame.
	Println(text string)

	// Clear clears the terminal and scrollback and repaints the mounted app.
	Clear()

	// Engine returns the underlying Kite Engine.
	Engine() *engine.Engine
}

AppHandle provides controls to interact with the running trail instance.

func UseApp

func UseApp() AppHandle

UseApp returns the AppHandle for the current trail application.

type FocusManager

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

FocusManager provides programmatic focus navigation controls for the active Document.

func UseFocusManager

func UseFocusManager() FocusManager

UseFocusManager returns a FocusManager to control document focus programmatically.

func (FocusManager) Blur

func (fm FocusManager) Blur()

Blur clears the current document focus.

func (FocusManager) Focus

func (fm FocusManager) Focus(id string) bool

Focus moves focus to the element with the specified ID.

func (FocusManager) FocusNext

func (fm FocusManager) FocusNext() bool

FocusNext moves focus to the next focusable element in the document.

func (FocusManager) FocusPrevious

func (fm FocusManager) FocusPrevious() bool

FocusPrevious moves focus to the previous focusable element in the document.

type FocusOptions

type FocusOptions struct {
	AutoFocus bool
	IsActive  bool
}

FocusOptions configures focus management for a focusable element.

type InputOptions

type InputOptions struct {
	IsActive bool
}

InputOptions configures keyboard input handling for UseInput.

type Instance

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

Instance manages the lifecycle of an inline trail application.

func Attach

func Attach(eng *engine.Engine, container dom.Element) *Instance

func New

func New(app kitex.Node, opts ...Option) (*Instance, error)

New initializes an inline trail Instance for the given root app component.

func Render

func Render(ctx context.Context, app kitex.Node, opts ...Option) (*Instance, error)

Render initializes an inline trail application, starts its event loop in a background goroutine, and returns the running Instance.

func (*Instance) Clear

func (inst *Instance) Clear()

Clear clears the terminal and scrollback, then repaints the mounted app from the top of the terminal without resetting component state.

func (*Instance) Engine

func (inst *Instance) Engine() *engine.Engine

Engine returns the underlying Kite Engine.

func (*Instance) Exit

func (inst *Instance) Exit(err error)

Exit signals the application to exit with an optional error.

func (*Instance) Frame

func (inst *Instance) Frame()

Frame runs a render pipeline pass and drains any follow-up pending tasks (such as passive effects queued during reconciliation), useful in headless tests.

func (*Instance) InsertAbove

func (inst *Instance) InsertAbove(node kitex.Node)

InsertAbove renders a kitex node into a temporary container and permanently flushes it to the terminal scrollback above the active inline frame.

func (*Instance) LogWriter

func (inst *Instance) LogWriter() io.Writer

LogWriter returns an io.Writer adapter that splits written bytes into lines and writes them permanently into the terminal scrollback above the active frame.

func (*Instance) Println

func (inst *Instance) Println(text string)

Println writes a text line above the inline frame.

func (*Instance) Rerender

func (inst *Instance) Rerender(app kitex.Node)

Rerender updates the root component tree with a new kitex.Node.

func (*Instance) Root

func (inst *Instance) Root(app kitex.Node) kitex.Node

func (*Instance) Run

func (inst *Instance) Run(ctx context.Context) error

Run executes the application event loop until context cancellation or Exit.

func (*Instance) Unmount

func (inst *Instance) Unmount()

Unmount unmounts the root VDOM tree (running effect cleanups) and exits the application.

func (*Instance) WaitUntilExit

func (inst *Instance) WaitUntilExit() error

WaitUntilExit blocks until the trail application completes and returns its exit error.

type Option

type Option func(*options)

Option configures a trail Instance.

func WithBackend

func WithBackend(b backend.Backend) Option

WithBackend specifies a custom backend (e.g. mock.New for testing).

func WithCtrlCExit

func WithCtrlCExit(enabled bool) Option

WithCtrlCExit enables or disables automatic exit when Ctrl+C is pressed.

func WithEngineOptions

func WithEngineOptions(opts engine.Options) Option

WithEngineOptions supplies custom engine.Options.

func WithInterceptLog

func WithInterceptLog(enabled bool) Option

WithInterceptLog redirects standard log output (log.Default()) above the inline frame during Run.

type StderrHandle

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

StderrHandle provides access to inline stderr routing above the inline frame.

func UseStderr

func UseStderr() StderrHandle

UseStderr returns a StderrHandle providing ink-compatible stderr write controls.

func (StderrHandle) Write

func (h StderrHandle) Write(s string)

Write writes text permanently into the terminal scrollback above the inline frame.

type StdoutHandle

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

StdoutHandle provides access to inline stdout routing and terminal sizing.

func UseStdout

func UseStdout() StdoutHandle

UseStdout returns a StdoutHandle providing ink-compatible stdout write and sizing controls.

func (StdoutHandle) Size

func (h StdoutHandle) Size() geom.Size

Size returns the current terminal viewport size.

func (StdoutHandle) Write

func (h StdoutHandle) Write(s string)

Write writes text permanently into the terminal scrollback above the inline frame.

Jump to

Keyboard shortcuts

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