Skip to content
Myr

Remove entire subscription model

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

It was a valiant effort, and the implementation was solid and dependable, but at the end of the day we can achieve the same functionality in a much simpler fashion with commands, especially because Go is not held to the same restrictions as Elm.

authored by Christian Rocha · committed by Christian Rocha · parent 82ddbb8 · Browse files · 13 files+136 added−322 removed
This commit

State

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

Diff stats

13 files+136 added−322 removed

  • other:+136 added−322 removed

13 files+136 added−322 removed

modified:examples/fullscreen/main.go+9 added-12 removed
12 unmodified lines
13type model int1415type tickMsg time.Time1617func newTickMsg(t time.Time) boba.Msg {18 return tickMsg(t)19}2017func main() {18 boba.AltScreen()19 defer boba.ExitAltScreen()24 err := boba.NewProgram(initialize, update, view, subscriptions).Start()20 err := boba.NewProgram(initialize, update, view).Start()21 if err != nil {22 log.Fatal(err)23 }24}2526func initialize() (boba.Model, boba.Cmd) {31 return model(5), nil27 return model(5), tick()28}2930func update(message boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {31 m, _ := mdl.(model)
14 unmodified lines
46 m -= 147 if m <= 0 {48 return m, boba.Quit49 }50 return m, tick()5152 }5354 return m, nil55}5660func subscriptions(_ boba.Model) boba.Subs {61 return boba.Subs{62 "tick": boba.Every(time.Second, newTickMsg),63 }64}6557func view(mdl boba.Model) string {58 m, _ := mdl.(model)59 return fmt.Sprintf("\n\n Hi. This program will exit in %d seconds...", m)60}6162func tick() boba.Cmd {63 return boba.Tick(time.Second, func(t time.Time) boba.Msg {64 return tickMsg(t)65 })66}
modified:examples/http/main.go+1 added-1 removed
21 unmodified lines
22type statusMsg int23type errMsg error2425func main() {26 p := boba.NewProgram(initialize, update, view, nil)26 p := boba.NewProgram(initialize, update, view)27 if err := p.Start(); err != nil {28 log.Fatal(err)29 }30}
59 unmodified lines
modified:examples/input/main.go+1 added-16 removed
20 unmodified lines
21 p := boba.NewProgram(22 initialize,23 update,24 view,25 subscriptions,25 )2627 if err := p.Start(); err != nil {28 log.Fatal(err)
7 unmodified lines
3637 return Model{38 textInput: inputModel,39 err: nil,41 }, nil40 }, input.Blink(inputModel)41}4243func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {44 var cmd boba.Cmd
27 unmodified lines
72 m.textInput, cmd = input.Update(msg, m.textInput)73 return m, cmd74}7577func subscriptions(model boba.Model) boba.Subs {78 m, ok := model.(Model)79 if !ok {80 return nil81 }82 sub, err := input.MakeSub(m.textInput)83 if err != nil {84 return nil85 }86 return boba.Subs{87 "input": sub,88 }89}9076func view(model boba.Model) string {77 m, ok := model.(Model)78 if !ok {79 return "Oh no: could not perform assertion on model."
9 unmodified lines
modified:examples/pager/main.go+5 added-1 removed
16 unmodified lines
17 }1819 boba.AltScreen()20 defer boba.ExitAltScreen()21 if err := pager.NewProgram(string(content)).Start(); err != nil {21 if err := boba.NewProgram(22 pager.Init(string(content)),23 pager.Update,24 pager.View,25 ).Start(); err != nil {26 fmt.Println("could not run program:", err)27 os.Exit(1)28 }29}
modified:examples/simple/main.go+11 added-15 removed
11 unmodified lines
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, all15// we'll need is a simple integer.16type Model int16type model int1718// Messages are events that we respond to in our Update function. This19// particular one indicates that the timer has ticked.20type tickMsg time.Time2122func main() {23 // Initialize our program24 p := boba.NewProgram(initialize, update, view, subscriptions)24 p := boba.NewProgram(initialize, update, view)25 if err := p.Start(); err != nil {26 log.Fatal(err)27 }28}2930func initialize() (boba.Model, boba.Cmd) {31 return Model(5), nil31 return model(5), tick32}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 boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {39 m, _ := model.(Model)38func update(msg boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {39 m, _ := mdl.(model)4041 switch msg.(type) {42 case boba.KeyMsg:43 return m, boba.Quit
1 unmodified line
45 m -= 146 if m <= 0 {47 return m, boba.Quit48 }49 return m, tick50 }51 return m, nil52}5354// Views take data from the model and return a string which will be rendered55// to the terminal.55func view(model boba.Model) string {56 m, _ := model.(Model)56func view(mdl boba.Model) string {57 m, _ := mdl.(model)58 return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)59}6060// This is a subscription which we setup in NewProgram(). It waits for one61// second, sends a tick, and then restarts.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 }61func tick() boba.Msg {62 time.Sleep(time.Second)63 return tickMsg{}64}
modified:examples/spinner/main.go+8 added-22 removed
20 unmodified lines
2122type errMsg error2324func main() {25 p := boba.NewProgram(initialize, update, view, subscriptions)25 p := boba.NewProgram(initialize, update, view)26 if err := p.Start(); err != nil {27 fmt.Println(err)28 os.Exit(1)29 }30}3132func initialize() (boba.Model, boba.Cmd) {33 m := spinner.NewModel()34 m.Type = spinner.Dot33 s := spinner.NewModel()34 s.Type = spinner.Dot3536 return Model{37 spinner: m,38 }, nil37 spinner: s,38 }, spinner.Tick(s)39}4041func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {42 m, ok := model.(Model)
20 unmodified lines
63 m.err = msg64 return m, nil6566 default:67 var cmd boba.Cmd67 m.spinner, _ = spinner.Update(msg, m.spinner)68 return m, nil68 m.spinner, cmd = spinner.Update(msg, m.spinner)69 return m, cmd70 }7172}73
14 unmodified lines
88 return str + "\n"89 }90 return str91}9192func subscriptions(model boba.Model) boba.Subs {93 m, ok := model.(Model)94 if !ok {95 return nil96 }9798 sub, err := spinner.MakeSub(m.spinner)99 if err != nil {100 return nil101 }102 return boba.Subs{103 "tick": sub,104 }105}
modified:examples/textinputs/main.go+25 added-33 removed
21 unmodified lines
22 if err := boba.NewProgram(23 initialize,24 update,25 view,26 subscriptions,26 ).Start(); err != nil {27 fmt.Printf("could not start program: %s\n", err)28 os.Exit(1)29 }
21 unmodified lines
51 email := input.NewModel()52 email.Placeholder = "Email"53 email.Prompt = blurredPrompt5456 return Model{0, name, nickName, email, blurredSubmitButton}, nil55 return Model{0, name, nickName, email, blurredSubmitButton},56 boba.Batch(57 input.Blink(name),58 input.Blink(nickName),59 input.Blink(email),60 )6162}6364func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {65 m, ok := model.(Model)66 if !ok {67 panic("could not perform assertion on model")68 }6970 var cmd boba.Cmd7172 switch msg := msg.(type) {7374 case boba.KeyMsg:75 switch msg.String() {
65 unmodified lines
141 return m, nil142143 default:144 // Handle character input138 m = updateInputs(msg, m)139 return m, nil145 m, cmd = updateInputs(msg, m)146 return m, cmd147 }148149 default:150 // Handle blinks144 m = updateInputs(msg, m)145 return m, nil151 m, cmd = updateInputs(msg, m)152 return m, cmd153 }154}155149func updateInputs(msg boba.Msg, m Model) Model {150 m.nameInput, _ = input.Update(msg, m.nameInput)151 m.nickNameInput, _ = input.Update(msg, m.nickNameInput)152 m.emailInput, _ = input.Update(msg, m.emailInput)153 return m156func updateInputs(msg boba.Msg, m Model) (Model, boba.Cmd) {157 var (158 cmd boba.Cmd159 cmds []boba.Cmd160 )161 m.nameInput, cmd = input.Update(msg, m.nameInput)162 cmds = append(cmds, cmd)163 m.nickNameInput, cmd = input.Update(msg, m.nickNameInput)164 cmds = append(cmds, cmd)165 m.emailInput, cmd = input.Update(msg, m.emailInput)166 cmds = append(cmds, cmd)167 return m, boba.Batch(cmds...)168}169156func subscriptions(model boba.Model) boba.Subs {157 m, ok := model.(Model)158 if !ok {159 return nil160 }161162 // It's a little hacky, but we're using the subscription from one163 // input element to handle the blinking for all elements. It doesn't164 // have to be this way, we're just feeling a bit lazy at the moment.165 inputSub, err := input.MakeSub(m.nameInput)166 if err != nil {167 return nil168 }169170 return boba.Subs{171 // It's a little hacky, but we're using the subscription from one172 // input element to handle the blinking for all elements. It doesn't173 // have to be this way, we're just feeling a bit lazy at the moment.174 "blink": inputSub,175 }176}177170func view(model boba.Model) string {171 m, ok := model.(Model)172 if !ok {173 return "[error] could not perform assertion on model"
21 unmodified lines
modified:examples/views/main.go+16 added-27 removed
1package main23// TODO: This code feels messy. Clean it up.3// TODO: The views feel messy. Clean 'em up.45import (6 "fmt"7 "math"
8 unmodified lines
16 p := boba.NewProgram(17 initialize,18 update,19 view,20 subscriptions,20 )21 if err := p.Start(); err != nil {22 fmt.Println("could not start program:", err)23 }24}2526// MSG2729type tickMsg time.Time28type tickMsg struct{}2931func newTickMsg(t time.Time) boba.Msg {32 return tickMsg(t)33}30type frameMsg struct{}3135type frameMsg time.Time3637func newFrameMsg(t time.Time) boba.Msg {38 return frameMsg(t)39}4032// MODEL3334// Model contains the data for our application.35type Model struct {
7 unmodified lines
4344// INIT4546func initialize() (boba.Model, boba.Cmd) {56 return Model{0, false, 10, 0, 0, false}, nil47 return Model{0, false, 10, 0, 0, false}, tick48}4959// SUBSCRIPTIONS50// CMDS5161func subscriptions(model boba.Model) boba.Subs {62 m, _ := model.(Model)63 if !m.Chosen || m.Loaded {64 return boba.Subs{65 "tick": boba.Every(time.Second, newTickMsg),66 }67 }68 return boba.Subs{69 "frame": boba.Every(time.Second/60, newFrameMsg),70 }52func tick() boba.Msg {53 time.Sleep(time.Second)54 return tickMsg{}55}5657func frame() boba.Msg {58 time.Sleep(time.Second / 60)59 return frameMsg{}60}6162// UPDATE6364func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {65 m, _ := model.(Model)
40 unmodified lines
106 }107 m.Ticks -= 1108 }109121 return m, nil110 return m, tick111}112113func updateChosen(msg boba.Msg, m Model) (boba.Model, boba.Cmd) {114 switch msg := msg.(type) {
10 unmodified lines
125126 case frameMsg:127 if !m.Loaded {128 m.Frames += 1140 m.Progress = ease.OutBounce(float64(m.Frames) / float64(120))129 m.Progress = ease.OutBounce(float64(m.Frames) / float64(160))130 if m.Progress >= 1 {131 m.Progress = 1132 m.Loaded = true133 m.Ticks = 3
8 unmodified lines
142 m.Ticks -= 1143 }144 }145157 return m, nil146 return m, frame147}148149// VIEW150
69 unmodified lines
modified:pager/pager.go-9 removed
7 unmodified lines
8 "github.com/charmbracelet/boba"9 "golang.org/x/crypto/ssh/terminal"10)1112func NewProgram(initialContent string) *boba.Program {13 return boba.NewProgram(14 Init(initialContent),15 Update,16 View,17 nil,18 )19}2012// MSG1314type terminalSizeMsg struct {15 width int
178 unmodified lines
modified:spinner/spinner.go+7 added-15 removed
1package spinner23import (4 "errors"4 "time"56 "github.com/charmbracelet/boba"7 "github.com/muesli/termenv"
14 unmodified lines
22 Line: {"|", "/", "-", "\\"},23 Dot: {"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},24 }2527 assertionErr = errors.New("could not perform assertion on model to what the spinner expects. are you sure you passed the right value?")2826 color = termenv.ColorProfile().Color27)2829// Model contains the state for the spinner. Use NewModel to create new models
16 unmodified lines
46 }47}4849// TickMsg indicates that the timer has ticked and we should render a frame53type TickMsg time.Time50type TickMsg struct{}5152// Update is the Boba update function53func Update(msg boba.Msg, m Model) (Model, boba.Cmd) {54 switch msg.(type) {
1 unmodified line
56 m.frame++57 if m.frame >= len(spinners[m.Type]) {58 m.frame = 059 }63 return m, nil60 return m, Tick(m)61 default:62 return m, nil63 }64}
17 unmodified lines
8283 return str84}8589// GetSub creates the subscription that allows the spinner to spin. Remember90// that you need to execute this function in order to get the subscription91// you'll need.92func MakeSub(model boba.Model) (boba.Sub, error) {93 m, ok := model.(Model)94 if !ok {95 return nil, assertionErr86// Tick is the command used to advance the spinner one frame.87func Tick(model Model) boba.Cmd {88 return func() boba.Msg {89 time.Sleep(time.Second / time.Duration(model.FPS))90 return TickMsg{}91 }97 return boba.Tick(time.Second/time.Duration(m.FPS), func(t time.Time) boba.Msg {98 return TickMsg(t)99 }), nil92}
modified:textinput/textinput.go+9 added-15 removed
1package textinput23import (4 "errors"4 "time"56 "github.com/charmbracelet/boba"7 "github.com/muesli/termenv"
67 unmodified lines
75 Foreground(color(m.PlaceholderColor)).76 String()77}7880// CursorBlinkMsg is sent when the cursor should alternate it's blinking state81type CursorBlinkMsg struct{}79// BlinkMsg is sent when the cursor should alternate it's blinking state80type BlinkMsg struct{}8182// NewModel creates a new model with default settings83func NewModel() Model {84 return Model{
77 unmodified lines
162 case ErrMsg:163 m.Err = msg164 return m, nil165167 case CursorBlinkMsg:166 case BlinkMsg:167 m.blink = !m.blink169 return m, nil168 return m, Blink(m)169170 default:171 return m, nil172 }
55 unmodified lines
228 Reverse().229 String()230}231233// MakeSub return a subscription that lets us know when to alternate the234// blinking of the cursor.235func MakeSub(model boba.Model) (boba.Sub, error) {236 m, ok := model.(Model)237 if !ok {238 return nil, errors.New("could not assert given model to the model we expected; make sure you're passing as input model")239 }232// Blink is a command used to time the cursor blinking.233func Blink(model Model) boba.Cmd {234 return func() boba.Msg {241 time.Sleep(m.BlinkSpeed)242 return CursorBlinkMsg{}243 }, nil235 time.Sleep(model.BlinkSpeed)236 return BlinkMsg{}237 }238}
modified:boba.go+44 added-124 removed
2 unmodified lines
3import (4 "io"5 "os"6 "strings"7 "time"89 "github.com/muesli/termenv"10)11
17 unmodified lines
29 return batchMsg(cmds)30 }31}3232// 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}6633// Init is the first function that will be called. It returns your initial34// model and runs an optional command35type Init func() (Model, Cmd)36
5 unmodified lines
42type View func(Model) string4344// Program is a terminal user interface45type Program struct {80 init Init81 update Update82 view View83 subscriptions Subscriptions46 init Init47 update Update48 view View49}5051// Quit is a command that tells the program to exit52func Quit() Msg {
6 unmodified lines
59// batchMsg is used to perform a bunch of commands60type batchMsg []Cmd6162// NewProgram creates a new Program98func NewProgram(init Init, update Update, view View, subs Subscriptions) *Program {63func NewProgram(init Init, update Update, view View) *Program {64 return &Program{100 init: init,101 update: update,102 view: view,103 subscriptions: subs,65 init: init,66 update: update,67 view: view,68 }69}7071// Start initializes the program72func (p *Program) Start() error {73 var (74 model Model75 cmd Cmd112 subs = make(subManager)76 cmds = make(chan Cmd)77 msgs = make(chan Msg)78 errs = make(chan error)79 done = make(chan struct{})
16 unmodified lines
9697 // Render initial view98 linesRendered = p.render(model, linesRendered)99137 // 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.100 // Subscribe to user input101 go func() {102 for {103 msg, err := ReadKey(os.Stdin)104 if err != nil {
2 unmodified lines
107 msgs <- KeyMsg(msg)108 }109 }()110150 // Initialize subscriptions151 subs = p.processSubs(msgs, model, subs)152111 // Process commands112 go func() {113 for {114 select {
32 unmodified lines
147 }148149 model, cmd = p.update(msg, model) // run update150 cmds <- cmd // process command (if any)193 subs = p.processSubs(msgs, model, subs) // check for new and outdated subscriptions151 linesRendered = p.render(model, linesRendered) // render to terminal152 }153 }154}
12 unmodified lines
167 _, _ = io.WriteString(os.Stdout, view)168 return strings.Count(view, "\r\n")169}170214// 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}285171// AltScreen exits the altscreen. This is just a wrapper around the termenv172// function173func AltScreen() {174 termenv.AltScreen()
3 unmodified lines
178// function179func ExitAltScreen() {180 termenv.ExitAltScreen()181}182183type EveryMsg time.Time184185// Every is a command that ticks in sync with the system clock. So, if you186// wanted to tick with the system clock every second, minute or hour you187// could use this. It's also handy for having different things tick in sync.188//189// Note that because we're ticking with the system clock the tick will likely190// not run for the entire specified duration. For example, if we're ticking for191// one minute and the clock is at 12:34:20 then the next tick will happen at192// 12:35:00, 40 seconds later.193func Every(duration time.Duration, fn func(time.Time) Msg) Cmd {194 return func() Msg {195 n := time.Now()196 d := n.Truncate(duration).Add(duration).Sub(n)197 t := time.NewTimer(d)198 select {199 case now := <-t.C:200 return fn(now)201 }202 }203}204205// Tick is a subscription that at an interval independent of the system clock206// at the given duration. That is, the timer begins when precisely when invoked,207// and runs for its entire duration.208func Tick(d time.Duration, fn func(time.Time) Msg) Cmd {209 return func() Msg {210 t := time.NewTimer(d)211 select {212 case now := <-t.C:213 return fn(now)214 }215 }216}
deleted:subscriptions.go-32 removed
1package boba23import (4 "time"5)67// Every is a subscription that ticks with the system clock at the given8// duration, similar to cron. It's particularly useful if you have several9// subscriptions that need to run in sync.10func Every(duration time.Duration, newMsg func(time.Time) Msg) Sub {11 return func() Msg {12 n := time.Now()13 d := n.Truncate(duration).Add(duration).Sub(n)14 t := time.NewTimer(d)15 select {16 case now := <-t.C:17 return newMsg(now)18 }19 }20}2122// Tick is a subscription that at an interval independent of the system clock23// at the given duration. That is, it begins precisely when invoked.24func Tick(d time.Duration, newMsg func(time.Time) Msg) Sub {25 return func() Msg {26 t := time.NewTimer(d)27 select {28 case now := <-t.C:29 return newMsg(now)30 }31 }32}