tea

package module
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2020 License: MIT Imports: 16 Imported by: 11,682

README

Bubble Tea

The fun, functional way to build terminal apps. A Go framework based on The Elm Architecture.

⚠️ This project is a pre-release so the API is subject to change a little. That said, we're using it in production.

Simple example

package main

// A simple program that counts down from 5 and then exits.

import (
	"fmt"
	"log"
	"time"
	tea "github.com/charmbracelet/bubbletea"
)

type model int

type tickMsg struct{}

func main() {
	p := tea.NewProgram(initialize, update, view, subscriptions)
	if err := p.Start(); err != nil {
		log.Fatal(err)
	}
}

// Return the initial model and initial command
func initialize() (tea.Model, tea.Cmd) {
    return 5, tick
}

// Listen for messages and update the model accordingly
func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {
	m, _ := mdl.(model)

	switch msg.(type) {
	case tickMsg:
		m--
		if m == 0 {
			return m, tea.Quit
		}
	}
	return m, nil
}

// Render to the terminal
func view(mdl tea.Model) string {
	m, _ := mdl.(model)
	return fmt.Sprintf("Hi. This program will exit in %d seconds...\n", m)
}

// A simple command which Bubble Tea runs asynchronously.
func tick() tea.Msg {
    time.Sleep(time.Second)
    return tickMsg{}
}

Hungry for more? Totally confused? See the other examples.

Other Resources

  • termenv: advanced ANSI style and color support for your terminal applications. Very useful when rendering your views.
  • reflow: a collection of ANSI-aware text formatting tools. Also useful for view rendering.
  • go-runewidth: functions to get the physical width of runes in terms of cells. Indispensable when working with fullwidth and zero-width characters.

Acknowledgments

Heavily inspired by both The Elm Architecture by Evan Czaplicki et al. and go-tea by TJ Holowaychuk.

License

MIT


Part of Charm.

the Charm logo

Charm热爱开源!

Documentation

Index

Constants

View Source
const (
	KeyNull      = keyNUL
	KeyBreak     = keyETX
	KeyEnter     = keyCR
	KeyBackspace = keyBS
	KeyTab       = keyHT
	KeySpace     = keySP
	KeyEsc       = keyESC
	KeyEscape    = keyESC
	KeyDelete    = keyDEL

	KeyCtrlAt           = keyNUL // ctrl+@
	KeyCtrlA            = keySOH
	KeyCtrlB            = keySTX
	KeyCtrlC            = keyETX
	KeyCtrlD            = keyEOT
	KeyCtrlE            = keyENQ
	KeyCtrlF            = keyACK
	KeyCtrlG            = keyBEL
	KeyCtrlH            = keyBS
	KeyCtrlI            = keyHT
	KeyCtrlJ            = keyLF
	KeyCtrlK            = keyVT
	KeyCtrlL            = keyFF
	KeyCtrlM            = keyCR
	KeyCtrlN            = keySO
	KeyCtrlO            = keySI
	KeyCtrlP            = keyDLE
	KeyCtrlQ            = keyDC1
	KeyCtrlR            = keyDC2
	KeyCtrlS            = keyDC3
	KeyCtrlT            = keyDC4
	KeyCtrlU            = keyNAK
	KeyCtrlV            = keyETB
	KeyCtrlW            = keyETB
	KeyCtrlX            = keyCAN
	KeyCtrlY            = keyEM
	KeyCtrlZ            = keySUB
	KeyCtrlOpenBracket  = keyESC // ctrl+[
	KeyCtrlBackslash    = keyFS  // ctrl+\
	KeyCtrlCloseBracket = keyGS  // ctrl+]
	KeyCtrlCaret        = keyRS  // ctrl+^
	KeyCtrlUnderscore   = keyUS  // ctrl+_
	KeyCtrlQuestionMark = keyDEL // ctrl+?
)

Aliases

View Source
const (
	KeyRune = -(iota + 1)
	KeyUp
	KeyDown
	KeyRight
	KeyLeft
	KeyShiftTab
	KeyHome
	KeyEnd
	KeyPgUp
	KeyPgDown
)

Other keys we track

Variables

This section is empty.

Functions

func AltScreen

func AltScreen()

AltScreen enters the alternate screen buffer.

func ExitAltScreen

func ExitAltScreen()

ExitAltScreen exits the alternate screen buffer.

func LogToFile

func LogToFile(path string, prefix string) (*os.File, error)

LogToFile sets up default logging to log to a file This is helpful as we can't print to the terminal since our TUI is occupying it. If the file doesn't exist it will be created.

Don't forget to close the file when you're done with it.

  f, err := LogToFile("debug.log", "debug")
  if err != nil {
		fmt.Println("fatal:", err)
		os.Exit(1)
  }
  defer f.Close()

func UseSysLog

func UseSysLog(programName string) error

UseSysLog sets up logging to log the system log. This becomes helpful when debugging since we can't print to the terminal since our TUI is occupying it.

On macOS this is a just a matter of: tail -f /var/log/system.log On Linux this varies depending on distribution.

Types

type Cmd

type Cmd func() Msg

Cmd is an IO operation. If it's nil it's considered a no-op. Keep in mind that there's almost never a need to use a command to send a message to another part of your program.

func Batch

func Batch(cmds ...Cmd) Cmd

Batch peforms a bunch of commands concurrently with no ordering guarantees about the results.

func Every

func Every(duration time.Duration, fn func(time.Time) Msg) Cmd

Every is a command that ticks in sync with the system clock. So, if you wanted to tick with the system clock every second, minute or hour you could use this. It's also handy for having different things tick in sync.

Because we're ticking with the system clock the tick will likely not run for the entire specified duration. For example, if we're ticking for one minute and the clock is at 12:34:20 then the next tick will happen at 12:35:00, 40 seconds later.

func ScrollDown added in v0.9.0

func ScrollDown(newLines []string, topBoundary, bottomBoundary int) Cmd

ScrollDown adds lines to the bottom of the scrollable region, pushing lines above up. Lines that are pushed out of the scrollable region disappear from view.

For high-performance, scroll-based rendering only.

func ScrollUp added in v0.9.0

func ScrollUp(newLines []string, topBoundary, bottomBoundary int) Cmd

ScrollUp adds lines to the top of the scrollable region, pushing lines below down. Lines that are pushed out the scrollable region disappear from view.

For high-performance, scroll-based rendering only.

func SyncScrollArea added in v0.9.0

func SyncScrollArea(lines []string, topBoundary int, bottomBoundary int) Cmd

SyncScrollArea performs a paint of the entire scroll area. This is required to initialize the scrollable region and should also be called on resize (WindowSizeMsg).

For high-performance, scroll-based rendering only.

func Tick

func Tick(d time.Duration, fn func(time.Time) Msg) Cmd

Tick is a command that at an interval independent of the system clock at the given duration. That is, the timer begins when precisely when invoked, and runs for its entire duration.

type Init

type Init func() (Model, Cmd)

Init is the first function that will be called. It returns your initial model and runs an optional command.

type Key

type Key struct {
	Type KeyType
	Rune rune
	Alt  bool
}

Key contains information about a keypress.

func ReadKey

func ReadKey(r io.Reader) (Key, error)

ReadKey reads keypress input from a TTY and returns a string representation of a key.

type KeyMsg

type KeyMsg Key

KeyMsg contains information about a keypress.

func (*KeyMsg) IsRune

func (k *KeyMsg) IsRune() bool

IsRune returns weather or not the key is a rune.

func (*KeyMsg) String

func (k *KeyMsg) String() (str string)

String returns a friendly name for a key.

type KeyType

type KeyType int

KeyType indicates the key pressed.

type Model

type Model interface{}

Model contains the program's state.

type Msg

type Msg interface{}

Msg represents an action and is usually the result of an IO operation. It's triggers the Update function, and henceforth, the UI.

func ClearScrollArea added in v0.9.0

func ClearScrollArea() Msg

ClearScrollArea deallocates the scrollable region and returns the control of those lines to the main rendering routine.

For high-performance, scroll-based rendering only.

func Quit

func Quit() Msg

Quit is a special command that tells the program to exit.

type Program

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

Program is a terminal user interface.

func NewProgram

func NewProgram(init Init, update Update, view View) *Program

NewProgram creates a new Program.

func (*Program) Start

func (p *Program) Start() error

Start initializes the program.

type Update

type Update func(Msg, Model) (Model, Cmd)

Update is called when a message is received. It may update the model and/or send a command.

type View

type View func(Model) string

View produces a string which will be rendered to the terminal.

type WindowSizeMsg added in v0.9.0

type WindowSizeMsg struct {
	Width  int
	Height int
}

WindowSizeMsg is used to report on the terminal size. It's sent once initially and then on every terminal resize.

Jump to

Keyboard shortcuts

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