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
Provenance
- Commit
ade8203- Tree
4c284b7- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
82ddbb8
13 files changed+136 added−322 removed
modified:examples/fullscreen/main.go+9 added-12 removed
12 unmodified lines13 type model int14 15 type tickMsg time.Time16 17-func newTickMsg(t time.Time) boba.Msg {18- return tickMsg(t)19-}20-17 func 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 }25 26 func initialize() (boba.Model, boba.Cmd) {31- return model(5), nil27+ return model(5), tick()28 }29 30 func update(message boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {31 m, _ := mdl.(model)14 unmodified lines46 m -= 147 if m <= 0 {48 return m, boba.Quit49 }50+ return m, tick()51 52 }53 54 return m, nil55 }56 60-func subscriptions(_ boba.Model) boba.Subs {61- return boba.Subs{62- "tick": boba.Every(time.Second, newTickMsg),63- }64-}65-57 func 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 }61+62+func 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 lines22 type statusMsg int23 type errMsg error24 25 func 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 linesmodified:examples/input/main.go+1 added-16 removed
20 unmodified lines21 p := boba.NewProgram(22 initialize,23 update,24 view,25- subscriptions,25 )26 27 if err := p.Start(); err != nil {28 log.Fatal(err)7 unmodified lines36 37 return Model{38 textInput: inputModel,39 err: nil,41- }, nil40+ }, input.Blink(inputModel)41 }42 43 func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {44 var cmd boba.Cmd27 unmodified lines72 m.textInput, cmd = input.Update(msg, m.textInput)73 return m, cmd74 }75 77-func 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-}90-76 func 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 linesmodified:examples/pager/main.go+5 added-1 removed
16 unmodified lines17 }18 19 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 lines12 13 // 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.16-type Model int16+type model int17 18 // Messages are events that we respond to in our Update function. This19 // particular one indicates that the timer has ticked.20 type tickMsg time.Time21 22 func 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 }29 30 func initialize() (boba.Model, boba.Cmd) {31- return Model(5), nil31+ return model(5), tick32 }33 34 // 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.38-func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {39- m, _ := model.(Model)38+func update(msg boba.Msg, mdl boba.Model) (boba.Model, boba.Cmd) {39+ m, _ := mdl.(model)40 41 switch msg.(type) {42 case boba.KeyMsg:43 return m, boba.Quit1 unmodified line45 m -= 146 if m <= 0 {47 return m, boba.Quit48 }49+ return m, tick50 }51 return m, nil52 }53 54 // Views take data from the model and return a string which will be rendered55 // to the terminal.55-func view(model boba.Model) string {56- m, _ := model.(Model)56+func 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 }60 60-// This is a subscription which we setup in NewProgram(). It waits for one61-// second, sends a tick, and then restarts.62-func 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- }61+func tick() boba.Msg {62+ time.Sleep(time.Second)63+ return tickMsg{}64 }modified:examples/spinner/main.go+8 added-22 removed
20 unmodified lines21 22 type errMsg error23 24 func 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 }31 32 func initialize() (boba.Model, boba.Cmd) {33- m := spinner.NewModel()34- m.Type = spinner.Dot33+ s := spinner.NewModel()34+ s.Type = spinner.Dot35 36 return Model{37- spinner: m,38- }, nil37+ spinner: s,38+ }, spinner.Tick(s)39 }40 41 func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {42 m, ok := model.(Model)20 unmodified lines63 m.err = msg64 return m, nil65 66 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 }71 72 }73 14 unmodified lines88 return str + "\n"89 }90 return str91 }91-92-func subscriptions(model boba.Model) boba.Subs {93- m, ok := model.(Model)94- if !ok {95- return nil96- }97-98- 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 lines22 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 lines51 email := input.NewModel()52 email.Placeholder = "Email"53 email.Prompt = blurredPrompt54 56- 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+ )61+62 }63 64 func 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 }69 70+ var cmd boba.Cmd71+72 switch msg := msg.(type) {73 74 case boba.KeyMsg:75 switch msg.String() {65 unmodified lines141 return m, nil142 143 default:144 // Handle character input138- m = updateInputs(msg, m)139- return m, nil145+ m, cmd = updateInputs(msg, m)146+ return m, cmd147 }148 149 default:150 // Handle blinks144- m = updateInputs(msg, m)145- return m, nil151+ m, cmd = updateInputs(msg, m)152+ return m, cmd153 }154 }155 149-func 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 m156+func 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 }169 156-func subscriptions(model boba.Model) boba.Subs {157- m, ok := model.(Model)158- if !ok {159- return nil160- }161-162- // 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- }169-170- 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-}177-170 func view(model boba.Model) string {171 m, ok := model.(Model)172 if !ok {173 return "[error] could not perform assertion on model"21 unmodified linesmodified:examples/views/main.go+16 added-27 removed
1 package main2 3-// TODO: This code feels messy. Clean it up.3+// TODO: The views feel messy. Clean 'em up.4 5 import (6 "fmt"7 "math"8 unmodified lines16 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 }25 26 // MSG27 29-type tickMsg time.Time28+type tickMsg struct{}29 31-func newTickMsg(t time.Time) boba.Msg {32- return tickMsg(t)33-}30+type frameMsg struct{}31 35-type frameMsg time.Time36-37-func newFrameMsg(t time.Time) boba.Msg {38- return frameMsg(t)39-}40-32 // MODEL33 34 // Model contains the data for our application.35 type Model struct {7 unmodified lines43 44 // INIT45 46 func initialize() (boba.Model, boba.Cmd) {56- return Model{0, false, 10, 0, 0, false}, nil47+ return Model{0, false, 10, 0, 0, false}, tick48 }49 59-// SUBSCRIPTIONS50+// CMDS51 61-func 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- }52+func tick() boba.Msg {53+ time.Sleep(time.Second)54+ return tickMsg{}55 }56 57+func frame() boba.Msg {58+ time.Sleep(time.Second / 60)59+ return frameMsg{}60+}61+62 // UPDATE63 64 func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {65 m, _ := model.(Model)40 unmodified lines106 }107 m.Ticks -= 1108 }109 121- return m, nil110+ return m, tick111 }112 113 func updateChosen(msg boba.Msg, m Model) (boba.Model, boba.Cmd) {114 switch msg := msg.(type) {10 unmodified lines125 126 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 = 38 unmodified lines142 m.Ticks -= 1143 }144 }145 157- return m, nil146+ return m, frame147 }148 149 // VIEW150 69 unmodified linesmodified:pager/pager.go-9 removed
7 unmodified lines8 "github.com/charmbracelet/boba"9 "golang.org/x/crypto/ssh/terminal"10 )11 12-func NewProgram(initialContent string) *boba.Program {13- return boba.NewProgram(14- Init(initialContent),15- Update,16- View,17- nil,18- )19-}20-12 // MSG13 14 type terminalSizeMsg struct {15 width int178 unmodified linesmodified:spinner/spinner.go+7 added-15 removed
1 package spinner2 3 import (4- "errors"4 "time"5 6 "github.com/charmbracelet/boba"7 "github.com/muesli/termenv"14 unmodified lines22 Line: {"|", "/", "-", "\\"},23 Dot: {"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},24 }25 27- assertionErr = errors.New("could not perform assertion on model to what the spinner expects. are you sure you passed the right value?")28-26 color = termenv.ColorProfile().Color27 )28 29 // Model contains the state for the spinner. Use NewModel to create new models16 unmodified lines46 }47 }48 49 // TickMsg indicates that the timer has ticked and we should render a frame53-type TickMsg time.Time50+type TickMsg struct{}51 52 // Update is the Boba update function53 func Update(msg boba.Msg, m Model) (Model, boba.Cmd) {54 switch msg.(type) {1 unmodified line56 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 lines82 83 return str84 }85 89-// 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.92-func 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.87+func 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
1 package textinput2 3 import (4- "errors"4 "time"5 6 "github.com/charmbracelet/boba"7 "github.com/muesli/termenv"67 unmodified lines75 Foreground(color(m.PlaceholderColor)).76 String()77 }78 80-// CursorBlinkMsg is sent when the cursor should alternate it's blinking state81-type CursorBlinkMsg struct{}79+// BlinkMsg is sent when the cursor should alternate it's blinking state80+type BlinkMsg struct{}81 82 // NewModel creates a new model with default settings83 func NewModel() Model {84 return Model{77 unmodified lines162 case ErrMsg:163 m.Err = msg164 return m, nil165 167- case CursorBlinkMsg:166+ case BlinkMsg:167 m.blink = !m.blink169- return m, nil168+ return m, Blink(m)169 170 default:171 return m, nil172 }55 unmodified lines228 Reverse().229 String()230 }231 233-// MakeSub return a subscription that lets us know when to alternate the234-// blinking of the cursor.235-func 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.233+func 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 lines3 import (4 "io"5 "os"6 "strings"7+ "time"8 9 "github.com/muesli/termenv"10 )11 17 unmodified lines29 return batchMsg(cmds)30 }31 }32 32-// 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.35-type Sub func() Msg36-37-// 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.40-type Subs map[string]Sub41-42-// Subscriptions returns a map of subscriptions (Subs) our application will43-// subscribe to. If Subscriptions is nil it's considered a no-op.44-type Subscriptions func(Model) Subs45-46-// subscription is an internal reference to a subscription used in subscription47-// management.48-type subscription struct {49- done chan struct{}50- sub Sub51-}52-53-// subManager is used to manage active subscriptions, hence the pointers.54-type subManager map[string]*subscription55-56-// endAll stops all subscriptions and remove subscription references from57-// subManager.58-func (m *subManager) endAll() {59- if m != nil {60- for key, sub := range *m {61- close(sub.done)62- delete(*m, key)63- }64- }65-}66-33 // Init is the first function that will be called. It returns your initial34 // model and runs an optional command35 type Init func() (Model, Cmd)36 5 unmodified lines42 type View func(Model) string43 44 // Program is a terminal user interface45 type Program struct {80- init Init81- update Update82- view View83- subscriptions Subscriptions46+ init Init47+ update Update48+ view View49 }50 51 // Quit is a command that tells the program to exit52 func Quit() Msg {6 unmodified lines59 // batchMsg is used to perform a bunch of commands60 type batchMsg []Cmd61 62 // NewProgram creates a new Program98-func NewProgram(init Init, update Update, view View, subs Subscriptions) *Program {63+func 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 }70 71 // Start initializes the program72 func (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 lines96 97 // Render initial view98 linesRendered = p.render(model, linesRendered)99 137- // 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 lines107 msgs <- KeyMsg(msg)108 }109 }()110 150- // Initialize subscriptions151- subs = p.processSubs(msgs, model, subs)152-111 // Process commands112 go func() {113 for {114 select {32 unmodified lines147 }148 149 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 lines167 _, _ = io.WriteString(os.Stdout, view)168 return strings.Count(view, "\r\n")169 }170 214-// 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.221-func (p *Program) processSubs(msgs chan Msg, model Model, activeSubs subManager) subManager {222-223- // Nothing to do.224- if p.subscriptions == nil && activeSubs == nil {225- return activeSubs226- }227-228- // There are no subscriptions. Cancel active ones and return.229- if p.subscriptions == nil && activeSubs != nil {230- activeSubs.endAll()231- return activeSubs232- }233-234- newSubs := p.subscriptions(model)235-236- // newSubs is an empty map. Cancel any active subscriptions and return.237- if newSubs == nil {238- activeSubs.endAll()239- return activeSubs240- }241-242- // 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- }253-254- // 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 {258-259- if sub == nil {260- continue261- }262-263- activeSubs[key] = &subscription{264- done: make(chan struct{}),265- sub: sub,266- }267-268- 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)278-279- }280- }281- }282-283- return activeSubs284-}285-171 // AltScreen exits the altscreen. This is just a wrapper around the termenv172 // function173 func AltScreen() {174 termenv.AltScreen()3 unmodified lines178 // function179 func ExitAltScreen() {180 termenv.ExitAltScreen()181 }182+183+type EveryMsg time.Time184+185+// 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.193+func 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+}204+205+// 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.208+func 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
1-package boba2-3-import (4- "time"5-)6-7-// 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.10-func 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-}21-22-// Tick is a subscription that at an interval independent of the system clock23-// at the given duration. That is, it begins precisely when invoked.24-func 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-}