Skip to content
Myr

Rename project to Boba

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christian Rocha · committed by Christian Rocha · parent 9dd9461 · Browse files · 17 files+391 added−379 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

17 files+391 added−379 removed

  • other:+391 added−379 removed

17 files+391 added−379 removed

modified:examples/fullscreen/main.go+14 added-14 removed
5 unmodified lines
6 "fmt"7 "log"8 "time"910 "github.com/charmbracelet/tea"10 "github.com/charmbracelet/boba"11)1213type model int1415type tickMsg time.Time1617func newTickMsg(t time.Time) tea.Msg {17func newTickMsg(t time.Time) boba.Msg {18 return tickMsg(t)19}2021func main() {22 tea.AltScreen()23 defer tea.ExitAltScreen()24 err := tea.NewProgram(initialize, update, view, subscriptions).Start()22 boba.AltScreen()23 defer boba.ExitAltScreen()24 err := boba.NewProgram(initialize, update, view, subscriptions).Start()25 if err != nil {26 log.Fatal(err)27 }28}2930func initialize() (tea.Model, tea.Cmd) {30func initialize() (boba.Model, boba.Cmd) {31 return model(5), nil32}3334func update(message tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {34func update(message boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {35 m, _ := mdl.(model)3637 switch msg := message.(type) {3839 case tea.KeyMsg:39 case boba.KeyMsg:40 switch msg.String() {41 case "ctrl+c":42 fallthrough43 case "esc":44 fallthrough45 case "q":46 return m, tea.Quit46 return m, boba.Quit47 }4849 case tickMsg:50 m -= 151 if m <= 0 {52 return m, tea.Quit52 return m, boba.Quit53 }5455 }5657 return m, nil58}5960func subscriptions(_ tea.Model) tea.Subs {61 return tea.Subs{62 "tick": tea.Every(time.Second, newTickMsg),60func subscriptions(_ boba.Model) boba.Subs {61 return boba.Subs{62 "tick": boba.Every(time.Second, newTickMsg),63 }64}6566func view(mdl tea.Model) string {66func view(mdl boba.Model) string {67 m, _ := mdl.(model)68 return fmt.Sprintf("\n\n Hi. This program will exit in %d seconds...", m)69}
modified:examples/http/main.go+9 added-9 removed
7 unmodified lines
8 "log"9 "net/http"10 "time"1112 "github.com/charmbracelet/tea"12 "github.com/charmbracelet/boba"13)1415const url = "https://charm.sh/"16
5 unmodified lines
22type statusMsg int23type errMsg error2425func main() {26 p := tea.NewProgram(initialize, update, view, nil)26 p := boba.NewProgram(initialize, update, view, nil)27 if err := p.Start(); err != nil {28 log.Fatal(err)29 }30}3132func initialize() (tea.Model, tea.Cmd) {32func initialize() (boba.Model, boba.Cmd) {33 return Model{0, nil}, checkServer34}3536func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {36func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {37 m, ok := model.(Model)38 if !ok {39 return Model{err: errors.New("could not perform assertion on model during update")}, nil40 }4142 switch msg := msg.(type) {4344 case tea.KeyMsg:44 case boba.KeyMsg:45 switch msg.String() {46 case "esc":47 fallthrough48 case "ctrl+c":49 fallthrough50 case "q":51 return m, tea.Quit51 return m, boba.Quit52 default:53 return m, nil54 }5556 case statusMsg:57 m.status = int(msg)58 return m, tea.Quit58 return m, boba.Quit5960 case errMsg:61 m.err = msg62 return m, nil
2 unmodified lines
65 return m, nil66 }67}6869func view(model tea.Model) string {69func view(model boba.Model) string {70 m, _ := model.(Model)71 s := fmt.Sprintf("Checking %s...", url)72 if m.err != nil {73 s += fmt.Sprintf("something went wrong: %s", m.err)
2 unmodified lines
76 }77 return s78}7980func checkServer() tea.Msg {80func checkServer() boba.Msg {81 c := &http.Client{82 Timeout: 10 * time.Second,83 }84 res, err := c.Get(url)
5 unmodified lines
modified:examples/input/main.go+13 added-13 removed
5 unmodified lines
6 "errors"7 "fmt"8 "log"910 "github.com/charmbracelet/tea"10 "github.com/charmbracelet/boba"11 "github.com/charmbracelet/teaparty/input"12)1314type Model struct {
4 unmodified lines
19type tickMsg struct{}20type errMsg error2122func main() {23 p := tea.NewProgram(23 p := boba.NewProgram(24 initialize,25 update,26 view,27 subscriptions,
3 unmodified lines
31 log.Fatal(err)32 }33}3435func initialize() (tea.Model, tea.Cmd) {35func initialize() (boba.Model, boba.Cmd) {36 inputModel := input.DefaultModel()37 inputModel.Placeholder = "Pikachu"3839 return Model{
1 unmodified line
41 err: nil,42 }, nil43}4445func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {46 var cmd tea.Cmd45func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {46 var cmd boba.Cmd47 m, ok := model.(Model)48 if !ok {49 // When we encounter errors in Update we simply add the error to the50 // model so we can handle it in the view. We could also return a command
3 unmodified lines
54 }, nil55 }5657 switch msg := msg.(type) {58 case tea.KeyMsg:58 case boba.KeyMsg:59 switch msg.Type {60 case tea.KeyCtrlC:60 case boba.KeyCtrlC:61 fallthrough62 case tea.KeyEsc:63 return m, tea.Quit62 case boba.KeyEsc:63 return m, boba.Quit64 }6566 // We handle errors just like any other message67 case errMsg:
4 unmodified lines
72 m.textInput, cmd = input.Update(msg, m.textInput)73 return m, cmd74}7576func subscriptions(model tea.Model) tea.Subs {77 return tea.Subs{76func subscriptions(model boba.Model) boba.Subs {77 return boba.Subs{78 // We just hand off the subscription to the input component, giving79 // it the model it expects.80 "input": func(model tea.Model) tea.Msg {80 "input": func(model boba.Model) boba.Msg {81 m, _ := model.(Model)82 return input.Blink(m.textInput)83 },84 }85}8687func view(model tea.Model) string {87func view(model boba.Model) string {88 m, ok := model.(Model)89 if !ok {90 return "Oh no: could not perform assertion on model."91 } else if m.err != nil {
8 unmodified lines
modified:examples/pager/main.go+3 added-3 removed
3 unmodified lines
4 "fmt"5 "io/ioutil"6 "os"78 "github.com/charmbracelet/tea"8 "github.com/charmbracelet/boba"9 "github.com/charmbracelet/teaparty/pager"10)1112func main() {
2 unmodified lines
15 fmt.Println("could not load file:", err)16 os.Exit(1)17 }1819 tea.AltScreen()20 defer tea.ExitAltScreen()19 boba.AltScreen()20 defer boba.ExitAltScreen()21 if err := pager.NewProgram(string(content)).Start(); err != nil {22 fmt.Println("could not run program:", err)23 os.Exit(1)24 }
1 unmodified line
modified:examples/simple/main.go+11 added-11 removed
5 unmodified lines
6 "fmt"7 "log"8 "time"910 "github.com/charmbracelet/tea"10 "github.com/charmbracelet/boba"11)1213// A model can be more or less any type of data. It holds all the data for a14// program, so often it's a struct. For this simple example, however, all
5 unmodified lines
20type tickMsg time.Time2122func main() {23 // Initialize our program24 p := tea.NewProgram(initialize, update, view, subscriptions)24 p := boba.NewProgram(initialize, update, view, subscriptions)25 if err := p.Start(); err != nil {26 log.Fatal(err)27 }28}2930func initialize() (tea.Model, tea.Cmd) {30func initialize() (boba.Model, boba.Cmd) {31 return Model(5), nil32}3334// Update is called when messages are recived. The idea is that you inspect35// the message and update the model (or send back a new one) accordingly. You36// can also return a commmand, which is a function that peforms I/O and37// returns a message.38func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {38func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {39 m, _ := model.(Model)4041 switch msg.(type) {42 case tea.KeyMsg:43 return m, tea.Quit42 case boba.KeyMsg:43 return m, boba.Quit44 case tickMsg:45 m -= 146 if m <= 0 {47 return m, tea.Quit47 return m, boba.Quit48 }49 }50 return m, nil51}5253// Views take data from the model and return a string which will be rendered54// to the terminal.55func view(model tea.Model) string {55func view(model boba.Model) string {56 m, _ := model.(Model)57 return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.", m)58}5960// This is a subscription which we setup in NewProgram(). It waits for one61// second, sends a tick, and then restarts.62func subscriptions(_ tea.Model) tea.Subs {63 return tea.Subs{64 "tick": tea.Every(time.Second, func(t time.Time) tea.Msg {62func subscriptions(_ boba.Model) boba.Subs {63 return boba.Subs{64 "tick": boba.Every(time.Second, func(t time.Time) boba.Msg {65 return tickMsg(t)66 }),67 }68}
modified:examples/spinner/main.go+9 added-9 removed
2 unmodified lines
3import (4 "fmt"5 "log"67 "github.com/charmbracelet/tea"7 "github.com/charmbracelet/boba"8 "github.com/charmbracelet/teaparty/spinner"9 "github.com/muesli/termenv"10)11
8 unmodified lines
2021type errMsg error2223func main() {24 p := tea.NewProgram(initialize, update, view, subscriptions)24 p := boba.NewProgram(initialize, update, view, subscriptions)25 if err := p.Start(); err != nil {26 log.Fatal(err)27 }28}2930func initialize() (tea.Model, tea.Cmd) {30func initialize() (boba.Model, boba.Cmd) {31 m := spinner.NewModel()32 m.Type = spinner.Dot3334 return Model{35 spinner: m,36 }, nil37}3839func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {39func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {40 m, ok := model.(Model)41 if !ok {42 return model, nil43 }4445 switch msg := msg.(type) {4647 case tea.KeyMsg:47 case boba.KeyMsg:48 switch msg.String() {49 case "q":50 fallthrough51 case "esc":52 fallthrough53 case "ctrl+c":54 return m, tea.Quit54 return m, boba.Quit55 default:56 return m, nil57 }58
7 unmodified lines
66 }6768}6970func view(model tea.Model) string {70func view(model boba.Model) string {71 m, ok := model.(Model)72 if !ok {73 return "could not perform assertion on model in view"74 }
6 unmodified lines
81 String()82 return fmt.Sprintf("\n\n %s Loading forever...press q to quit\n\n", s)83}8485func subscriptions(model tea.Model) tea.Subs {85func subscriptions(model boba.Model) boba.Subs {86 m, ok := model.(Model)87 if !ok {88 return nil89 }
1 unmodified line
91 sub, err := spinner.MakeSub(m.spinner)92 if err != nil {93 return nil94 }95 return tea.Subs{95 return boba.Subs{96 "tick": sub,97 }98}
modified:examples/go.mod+4 added-3 removed
1module examples23go 1.1345replace github.com/charmbracelet/tea => ../5replace github.com/charmbracelet/boba => ../67require (8 github.com/charmbracelet/tea v0.0.0-20200130023737-bb06373836b49 github.com/charmbracelet/teaparty v0.0.0-20200212224515-b4d35fd529068 github.com/charmbracelet/boba v0.0.0-00010101000000-0000000000009 github.com/charmbracelet/tea v0.3.010 github.com/charmbracelet/teaparty v0.0.0-20200511213328-a72bf9128d8311 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf177612 github.com/muesli/termenv v0.5.213)
modified:examples/go.sum+9 added
1github.com/charmbracelet/tea v0.0.0-20200130023737-bb06373836b4 h1:O8IGyYrKQuCwZZ98JP3DvzQCoPiXM5Y2zjwlDY7mOFM=2github.com/charmbracelet/tea v0.0.0-20200130023737-bb06373836b4/go.mod h1:UsFFdg04MNbcYi1r2FBtdDEFY07bObaYDKHhE1xZUaQ=3github.com/charmbracelet/tea v0.3.0 h1:W5F1x/IYeSCKpZl3/hM3Mn5v2KAagckabDFhhzh5sIE=4github.com/charmbracelet/tea v0.3.0/go.mod h1:uA/DUzCuyIZ1NFyAdCz6k+gF8lspujo6ZvoavcSsLCM=5github.com/charmbracelet/teaparty v0.0.0-20200212224515-b4d35fd52906 h1:kcvv+hjb0dJiqhtMXkql5tczxalWMPvKIqwWo7cyhiQ=6github.com/charmbracelet/teaparty v0.0.0-20200212224515-b4d35fd52906/go.mod h1:BG6oiwNZL9hB739ZOifRi3ePRGv0nT+kRTfxYLcZj/Y=7github.com/charmbracelet/teaparty v0.0.0-20200511213328-a72bf9128d83 h1:ivIS4ze0LLG9yl9L8cnYerh6dWnqhmBqh1ohmrA3I/I=8github.com/charmbracelet/teaparty v0.0.0-20200511213328-a72bf9128d83/go.mod h1:rlnGPwUokLHs2rQBiIYg6fpLM5m4DvtE2LwzdvS1wsk=9github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=10github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=11github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=12github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=
6 unmodified lines
19github.com/muesli/termenv v0.5.2/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=20github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942 h1:A7GG7zcGjl3jqAqGPmcNjd/D9hzL95SuoOQAaFNdLU0=21github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ=22golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=23golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=24golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 h1:1/DFK4b7JH8DmkqhUk48onnSfrPzImPoVxuomtbT2nk=25golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=26golang.org/x/sys v0.0.0-20200430202703-d923437fa56d h1:xmcims+WSpFuY56YEzkKF6IMDxYAVDRipkQRJfXUBZk=27golang.org/x/sys v0.0.0-20200430202703-d923437fa56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=28golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f h1:mOhmO9WsBaJCNmaZHPtHs9wOcdqdKCjF6OPJlmDM3KI=29golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
added:boba.go+296 added
1package boba23import (4 "io"5 "os"6 "strings"78 "github.com/muesli/termenv"9)1011// Msg represents an action and is usually the result of an IO operation. It's12// triggers the Update function, and henceforth, the UI.13type Msg interface{}1415// Model contains the program's state.16type Model interface{}1718// Cmd is an IO operation that runs once. If it's nil it's considered a no-op.19type Cmd func() Msg2021// Batch peforms a bunch of commands concurrently with no ordering guarantees22// about the results.23func Batch(cmds ...Cmd) Cmd {24 if len(cmds) == 0 {25 return nil26 }27 return func() Msg {28 return batchMsg(cmds)29 }30}3132// Sub is an event subscription; generally a recurring IO operation. If it33// returns nil it's considered a no-op, but there's really no reason to have34// a nil subscription.35type Sub func() Msg3637// Subs is a keyed set of subscriptions. The key should be a unique38// identifier: two different subscriptions should not have the same key or39// weird behavior will occur.40type Subs map[string]Sub4142// Subscriptions returns a map of subscriptions (Subs) our application will43// subscribe to. If Subscriptions is nil it's considered a no-op.44type Subscriptions func(Model) Subs4546// subscription is an internal reference to a subscription used in subscription47// management.48type subscription struct {49 done chan struct{}50 sub Sub51}5253// subManager is used to manage active subscriptions, hence the pointers.54type subManager map[string]*subscription5556// endAll stops all subscriptions and remove subscription references from57// subManager.58func (m *subManager) endAll() {59 if m != nil {60 for key, sub := range *m {61 close(sub.done)62 delete(*m, key)63 }64 }65}6667// Init is the first function that will be called. It returns your initial68// model and runs an optional command69type Init func() (Model, Cmd)7071// Update is called when a message is received. It may update the model and/or72// send a command.73type Update func(Msg, Model) (Model, Cmd)7475// View produces a string which will be rendered to the terminal76type View func(Model) string7778// Program is a terminal user interface79type Program struct {80 init Init81 update Update82 view View83 subscriptions Subscriptions84}8586// Quit is a command that tells the program to exit87func Quit() Msg {88 return quitMsg{}89}9091// Signals that the program should quit92type quitMsg struct{}9394// batchMsg is used to perform a bunch of commands95type batchMsg []Cmd9697// NewProgram creates a new Program98func NewProgram(init Init, update Update, view View, subs Subscriptions) *Program {99 return &Program{100 init: init,101 update: update,102 view: view,103 subscriptions: subs,104 }105}106107// Start initializes the program108func (p *Program) Start() error {109 var (110 model Model111 cmd Cmd112 subs = make(subManager)113 cmds = make(chan Cmd)114 msgs = make(chan Msg)115 errs = make(chan error)116 done = make(chan struct{})117 linesRendered int118 )119120 err := initTerminal()121 if err != nil {122 return err123 }124 defer restoreTerminal()125126 // Initialize program127 model, cmd = p.init()128 if cmd != nil {129 go func() {130 cmds <- cmd131 }()132 }133134 // Render initial view135 linesRendered = p.render(model, linesRendered)136137 // Subscribe to user input. We could move this out of here and offer it138 // as a subscription, but it blocks nicely and seems to be a common enough139 // need that we're enabling it by default.140 go func() {141 for {142 msg, err := ReadKey(os.Stdin)143 if err != nil {144 errs <- err145 }146 msgs <- KeyMsg(msg)147 }148 }()149150 // Initialize subscriptions151 subs = p.processSubs(msgs, model, subs)152153 // Process commands154 go func() {155 for {156 select {157 case <-done:158 return159 case cmd := <-cmds:160 if cmd != nil {161 go func() {162 msgs <- cmd()163 }()164 }165 }166 }167 }()168169 // Handle updates and draw170 for {171 select {172 case err := <-errs:173 close(done)174 return err175 case msg := <-msgs:176177 // Handle quit message178 if _, ok := msg.(quitMsg); ok {179 close(done)180 return nil181 }182183 // Process batch commands184 if batchedCmds, ok := msg.(batchMsg); ok {185 for _, cmd := range batchedCmds {186 cmds <- cmd187 }188 continue189 }190191 model, cmd = p.update(msg, model) // run update192 cmds <- cmd // process command (if any)193 subs = p.processSubs(msgs, model, subs) // check for new and outdated subscriptions194 linesRendered = p.render(model, linesRendered) // render to terminal195 }196 }197}198199// Render a view to the terminal. Returns the number of lines rendered.200func (p *Program) render(model Model, linesRendered int) int {201 view := p.view(model)202203 // We need to add carriage returns to ensure that the cursor travels to the204 // start of a column after a newline205 view = strings.Replace(view, "\n", "\r\n", -1)206207 if linesRendered > 0 {208 termenv.ClearLines(linesRendered)209 }210 _, _ = io.WriteString(os.Stdout, view)211 return strings.Count(view, "\r\n")212}213214// Manage subscriptions. Here we run the program's Subscription function and215// inspect the functions it returns (a Subs map). If we notice existing216// subscriptions have disappeared from the map we stop those subscriptions217// by ending the Goroutines they run on. If we notice new subscriptions which218// aren't currently running, we run them as loops in a new Goroutine.219//220// This function should be called on initialization and after every update.221func (p *Program) processSubs(msgs chan Msg, model Model, activeSubs subManager) subManager {222223 // Nothing to do.224 if p.subscriptions == nil && activeSubs == nil {225 return activeSubs226 }227228 // There are no subscriptions. Cancel active ones and return.229 if p.subscriptions == nil && activeSubs != nil {230 activeSubs.endAll()231 return activeSubs232 }233234 newSubs := p.subscriptions(model)235236 // newSubs is an empty map. Cancel any active subscriptions and return.237 if newSubs == nil {238 activeSubs.endAll()239 return activeSubs240 }241242 // Stop subscriptions that don't exist in the new subscription map and243 // stop subscriptions where the new subscription is mapped to a nil.244 if len(activeSubs) > 0 {245 for key, sub := range activeSubs {246 _, exists := newSubs[key]247 if !exists || exists && newSubs[key] == nil {248 close(sub.done)249 delete(activeSubs, key)250 }251 }252 }253254 // Start new subscriptions if they don't exist in the active subscription map255 if len(newSubs) > 0 {256 for key, sub := range newSubs {257 if _, exists := activeSubs[key]; !exists {258259 if sub == nil {260 continue261 }262263 activeSubs[key] = &subscription{264 done: make(chan struct{}),265 sub: sub,266 }267268 go func(done chan struct{}, s Sub) {269 for {270 select {271 case <-done:272 return273 case msgs <- s():274 continue275 }276 }277 }(activeSubs[key].done, activeSubs[key].sub)278279 }280 }281 }282283 return activeSubs284}285286// AltScreen exits the altscreen. This is just a wrapper around the termenv287// function288func AltScreen() {289 termenv.AltScreen()290}291292// ExitAltScreen exits the altscreen. This is just a wrapper around the termenv293// function294func ExitAltScreen() {295 termenv.ExitAltScreen()296}
modified:go.mod+1 added-1 removed
1module github.com/charmbracelet/tea1module github.com/charmbracelet/boba23go 1.1345require (
4 unmodified lines
modified:key.go+1 added-1 removed
1package tea1package boba23import (4 "errors"5 "fmt"
279 unmodified lines
modified:logging.go+1 added-1 removed
1// +build darwin dragonfly freebsd linux netbsd openbsd solaris23package tea3package boba45import (6 "log"7 "log/syslog"
15 unmodified lines
modified:README.md+17 added-15 removed
1# Tea1# Boba23The fun, functional way to build terminal apps. A Go framework based on4[The Elm Architecture][elm]. 茶!4[The Elm Architecture][elm].56⚠️ This project is a pre-release! The API is subject to change a little.6⚠️ This project is a pre-release so the API is subject to change7a little. That said, we're using it in production.8910## Simple example1112```go13package main
3 unmodified lines
17import (18 "fmt"19 "log"20 "time"19 "github.com/charmbracelet/tea"21 "github.com/charmbracelet/boba"22)2324type model int2526type tickMsg time.Time2728func main() {27 p := tea.NewProgram(init, update, view, subscriptions)29 p := boba.NewProgram(init, update, view, subscriptions)30 if err := p.Start(); err != nil {31 log.Fatal(err)32 }33}3435// Listen for messages and update the model accordingly34func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {36func update(msg boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {37 m, _ := mdl.(model)3839 switch msg.(type) {40 case tickMsg:41 m--42 if m == 0 {41 return m, tea.Quit43 return m, boba.Quit44 }45 }46 return m, nil47}4849// Render to the terminal48func view(mdl tea.Model) string {50func view(mdl boba.Model) string {51 m, _ := mdl.(model)52 return fmt.Sprintf("Hi. This program will exit in %d seconds...\n", m)53}5455// Subscribe to events54func subscriptions(_ tea.Model) tea.Subs {55 return tea.Subs{56 "tick": time.Every(time.Second, func(t time.Time) tea.Msg {56func subscriptions(_ boba.Model) boba.Subs {57 return boba.Subs{58 "tick": time.Every(time.Second, func(t time.Time) boba.Msg {59 return tickMsg(t)60 },61 }62}63```6465Hungry for more? See the [other examples][examples].6665[examples]: https://github.com/charmbracelet/tea/tree/master/examples67[examples]: https://github.com/charmbracelet/boba/tree/master/examples686970## Other Resources7169* [Tea Party](https://github.com/charmbracelet/teaparty): a collection of Tea70 components.72* [Termenv](https://github.com/muesli/termenv): advanced ANSI style and color73 support for your terminal applications. Very useful when rendering your74 views.75* [Reflow](https://github.com/muesli/reflow): a collection of ANSI-aware text
7 unmodified lines
8384[elm]: https://guide.elm-lang.org/architecture/85[gotea]: https://github.com/tj/go-tea868788## License8988[MIT](https://github.com/charmbracelet/tea/raw/master/LICENSE)90[MIT](https://github.com/charmbracelet/boba/raw/master/LICENSE)9192***9394Part of [Charm](https://charm.sh).
4 unmodified lines
modified:subscriptions.go+1 added-1 removed
1package tea1package boba23import (4 "time"5)
27 unmodified lines
deleted:tea.go-296 removed
1package tea23import (4 "io"5 "os"6 "strings"78 "github.com/muesli/termenv"9)1011// Msg represents an action and is usually the result of an IO operation. It's12// triggers the Update function, and henceforth, the UI.13type Msg interface{}1415// Model contains the program's state.16type Model interface{}1718// Cmd is an IO operation that runs once. If it's nil it's considered a no-op.19type Cmd func() Msg2021// Batch peforms a bunch of commands concurrently with no ordering guarantees22// about the results.23func Batch(cmds ...Cmd) Cmd {24 if len(cmds) == 0 {25 return nil26 }27 return func() Msg {28 return batchMsg(cmds)29 }30}3132// Sub is an event subscription; generally a recurring IO operation. If it33// returns nil it's considered a no-op, but there's really no reason to have34// a nil subscription.35type Sub func() Msg3637// Subs is a keyed set of subscriptions. The key should be a unique38// identifier: two different subscriptions should not have the same key or39// weird behavior will occur.40type Subs map[string]Sub4142// Subscriptions returns a map of subscriptions (Subs) our application will43// subscribe to. If Subscriptions is nil it's considered a no-op.44type Subscriptions func(Model) Subs4546// subscription is an internal reference to a subscription used in subscription47// management.48type subscription struct {49 done chan struct{}50 sub Sub51}5253// subManager is used to manage active subscriptions, hence the pointers.54type subManager map[string]*subscription5556// endAll stops all subscriptions and remove subscription references from57// subManager.58func (m *subManager) endAll() {59 if m != nil {60 for key, sub := range *m {61 close(sub.done)62 delete(*m, key)63 }64 }65}6667// Init is the first function that will be called. It returns your initial68// model and runs an optional command69type Init func() (Model, Cmd)7071// Update is called when a message is received. It may update the model and/or72// send a command.73type Update func(Msg, Model) (Model, Cmd)7475// View produces a string which will be rendered to the terminal76type View func(Model) string7778// Program is a terminal user interface79type Program struct {80 init Init81 update Update82 view View83 subscriptions Subscriptions84}8586// Quit is a command that tells the program to exit87func Quit() Msg {88 return quitMsg{}89}9091// Signals that the program should quit92type quitMsg struct{}9394// batchMsg is used to perform a bunch of commands95type batchMsg []Cmd9697// NewProgram creates a new Program98func NewProgram(init Init, update Update, view View, subs Subscriptions) *Program {99 return &Program{100 init: init,101 update: update,102 view: view,103 subscriptions: subs,104 }105}106107// Start initializes the program108func (p *Program) Start() error {109 var (110 model Model111 cmd Cmd112 subs = make(subManager)113 cmds = make(chan Cmd)114 msgs = make(chan Msg)115 errs = make(chan error)116 done = make(chan struct{})117 linesRendered int118 )119120 err := initTerminal()121 if err != nil {122 return err123 }124 defer restoreTerminal()125126 // Initialize program127 model, cmd = p.init()128 if cmd != nil {129 go func() {130 cmds <- cmd131 }()132 }133134 // Render initial view135 linesRendered = p.render(model, linesRendered)136137 // Subscribe to user input. We could move this out of here and offer it138 // as a subscription, but it blocks nicely and seems to be a common enough139 // need that we're enabling it by default.140 go func() {141 for {142 msg, err := ReadKey(os.Stdin)143 if err != nil {144 errs <- err145 }146 msgs <- KeyMsg(msg)147 }148 }()149150 // Initialize subscriptions151 subs = p.processSubs(msgs, model, subs)152153 // Process commands154 go func() {155 for {156 select {157 case <-done:158 return159 case cmd := <-cmds:160 if cmd != nil {161 go func() {162 msgs <- cmd()163 }()164 }165 }166 }167 }()168169 // Handle updates and draw170 for {171 select {172 case err := <-errs:173 close(done)174 return err175 case msg := <-msgs:176177 // Handle quit message178 if _, ok := msg.(quitMsg); ok {179 close(done)180 return nil181 }182183 // Process batch commands184 if batchedCmds, ok := msg.(batchMsg); ok {185 for _, cmd := range batchedCmds {186 cmds <- cmd187 }188 continue189 }190191 model, cmd = p.update(msg, model) // run update192 cmds <- cmd // process command (if any)193 subs = p.processSubs(msgs, model, subs) // check for new and outdated subscriptions194 linesRendered = p.render(model, linesRendered) // render to terminal195 }196 }197}198199// Render a view to the terminal. Returns the number of lines rendered.200func (p *Program) render(model Model, linesRendered int) int {201 view := p.view(model)202203 // We need to add carriage returns to ensure that the cursor travels to the204 // start of a column after a newline205 view = strings.Replace(view, "\n", "\r\n", -1)206207 if linesRendered > 0 {208 termenv.ClearLines(linesRendered)209 }210 _, _ = io.WriteString(os.Stdout, view)211 return strings.Count(view, "\r\n")212}213214// Manage subscriptions. Here we run the program's Subscription function and215// inspect the functions it returns (a Subs map). If we notice existing216// subscriptions have disappeared from the map we stop those subscriptions217// by ending the Goroutines they run on. If we notice new subscriptions which218// aren't currently running, we run them as loops in a new Goroutine.219//220// This function should be called on initialization and after every update.221func (p *Program) processSubs(msgs chan Msg, model Model, activeSubs subManager) subManager {222223 // Nothing to do.224 if p.subscriptions == nil && activeSubs == nil {225 return activeSubs226 }227228 // There are no subscriptions. Cancel active ones and return.229 if p.subscriptions == nil && activeSubs != nil {230 activeSubs.endAll()231 return activeSubs232 }233234 newSubs := p.subscriptions(model)235236 // newSubs is an empty map. Cancel any active subscriptions and return.237 if newSubs == nil {238 activeSubs.endAll()239 return activeSubs240 }241242 // Stop subscriptions that don't exist in the new subscription map and243 // stop subscriptions where the new subscription is mapped to a nil.244 if len(activeSubs) > 0 {245 for key, sub := range activeSubs {246 _, exists := newSubs[key]247 if !exists || exists && newSubs[key] == nil {248 close(sub.done)249 delete(activeSubs, key)250 }251 }252 }253254 // Start new subscriptions if they don't exist in the active subscription map255 if len(newSubs) > 0 {256 for key, sub := range newSubs {257 if _, exists := activeSubs[key]; !exists {258259 if sub == nil {260 continue261 }262263 activeSubs[key] = &subscription{264 done: make(chan struct{}),265 sub: sub,266 }267268 go func(done chan struct{}, s Sub) {269 for {270 select {271 case <-done:272 return273 case msgs <- s():274 continue275 }276 }277 }(activeSubs[key].done, activeSubs[key].sub)278279 }280 }281 }282283 return activeSubs284}285286// AltScreen exits the altscreen. This is just a wrapper around the termenv287// function288func AltScreen() {289 termenv.AltScreen()290}291292// ExitAltScreen exits the altscreen. This is just a wrapper around the termenv293// function294func ExitAltScreen() {295 termenv.ExitAltScreen()296}
modified:tty_unix.go+1 added-1 removed
1// +build darwin dragonfly freebsd linux netbsd openbsd solaris23package tea3package boba45import (6 "github.com/muesli/termenv"7 "github.com/pkg/term"
26 unmodified lines
modified:tty_windows.go+1 added-1 removed
1// +build windows23package tea3package boba45import "github.com/muesli/termenv"67func initTerminal() error {
7 unmodified lines