Move components over and update examples
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 4bf40fb · Browse files · 15 files·+1002 added−57 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+1002 added−57 removed
- other:+1002 added−57 removed
Provenance
- Commit
82ddbb8- Tree
7f6e2d2- Author
Christian Rocha <christian@rocha.is>- Committer
Christian Rocha <christian@rocha.is>- Parent
4bf40fb
15 files changed+1002 added−57 removed
modified:examples/http/main.go+1 added-1 removed
72 unmodified lines73 s += fmt.Sprintf("something went wrong: %s", m.err)74 } else if m.status != 0 {75 s += fmt.Sprintf("%d %s", m.status, http.StatusText(m.status))76 }77- return s77+ return s + "\n"78 }79 80 func checkServer() boba.Msg {81 c := &http.Client{8 unmodified linesmodified:examples/input/main.go+15 added-11 removed
1 package main2 3-// A simple program that counts down from 5 and then exits.4-3 import (4 "errors"5 "fmt"6 "log"7 8 "github.com/charmbracelet/boba"11- "github.com/charmbracelet/teaparty/input"9+ input "github.com/charmbracelet/boba/textinput"10 )11 12 type Model struct {13 textInput input.Model16 unmodified lines30 }31 }32 33 func initialize() (boba.Model, boba.Cmd) {36- inputModel := input.DefaultModel()34+ inputModel := input.NewModel()35 inputModel.Placeholder = "Pikachu"36+ inputModel.Focus()37 38 return Model{39 textInput: inputModel,40 err: nil,17 unmodified lines58 switch msg.Type {59 case boba.KeyCtrlC:60 fallthrough61 case boba.KeyEsc:62+ fallthrough63+ case boba.KeyEnter:64 return m, boba.Quit65 }66 67 // We handle errors just like any other message6 unmodified lines74 return m, cmd75 }76 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{78- // We just hand off the subscription to the input component, giving79- // it the model it expects.80- "input": func(model boba.Model) boba.Msg {81- m, _ := model.(Model)82- return input.Blink(m.textInput)83- },87+ "input": sub,88 }89 }90 91 func view(model boba.Model) string {6 unmodified lines98 return fmt.Sprintf(99 "What’s your favorite Pokémon?\n\n%s\n\n%s",100 input.View(m.textInput),101 "(esc to quit)",98- )102+ ) + "\n"103 }modified:examples/pager/main.go+1 added-1 removed
4 unmodified lines5 "io/ioutil"6 "os"7 8 "github.com/charmbracelet/boba"9- "github.com/charmbracelet/teaparty/pager"9+ "github.com/charmbracelet/boba/pager"10 )11 12 func main() {13 content, err := ioutil.ReadFile("artichoke.md")12 unmodified linesmodified:examples/simple/main.go+1 added-1 removed
52 unmodified lines53 // Views take data from the model and return a string which will be rendered54 // to the terminal.55 func 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)57+ return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)58 }59 60 // This is a subscription which we setup in NewProgram(). It waits for one61 // second, sends a tick, and then restarts.7 unmodified linesmodified:examples/spinner/main.go+14 added-7 removed
1 package main2 3 import (4 "fmt"5- "log"5+ "os"6 7 "github.com/charmbracelet/boba"8- "github.com/charmbracelet/teaparty/spinner"8+ "github.com/charmbracelet/boba/spinner"9 "github.com/muesli/termenv"10 )11 12 var (13 color = termenv.ColorProfile()14 )15 16 type Model struct {17- spinner spinner.Model18- err error17+ spinner spinner.Model18+ quitting bool19+ err error20 }21 22 type errMsg error23 24 func main() {25 p := boba.NewProgram(initialize, update, view, subscriptions)26 if err := p.Start(); err != nil {26- log.Fatal(err)27+ fmt.Println(err)28+ os.Exit(1)29 }30 }31 32 func initialize() (boba.Model, boba.Cmd) {19 unmodified lines52 fallthrough53 case "esc":54 fallthrough55 case "ctrl+c":56+ m.quitting = true57 return m, boba.Quit58 default:59 return m, nil60 }11 unmodified lines72 73 func view(model boba.Model) string {74 m, ok := model.(Model)75 if !ok {73- return "could not perform assertion on model in view"76+ return "could not perform assertion on model in view\n"77 }78 if m.err != nil {79 return m.err.Error()80 }81 s := termenv.82 String(spinner.View(m.spinner)).83 Foreground(color.Color("205")).84 String()82- return fmt.Sprintf("\n\n %s Loading forever...press q to quit\n\n", s)85+ str := fmt.Sprintf("\n\n %s Loading forever...press q to quit\n\n", s)86+ if m.quitting {87+ return str + "\n"88+ }89+ return str90 }91 92 func subscriptions(model boba.Model) boba.Subs {93 m, ok := model.(Model)12 unmodified linesadded:examples/textinputs/main.go+202 added
1+package main2+3+import (4+ "fmt"5+ "os"6+7+ "github.com/charmbracelet/boba"8+ input "github.com/charmbracelet/boba/textinput"9+ te "github.com/muesli/termenv"10+)11+12+var (13+ color = te.ColorProfile().Color14+ focusedText = "205"15+ focusedPrompt = te.String("> ").Foreground(color("205")).String()16+ blurredPrompt = "> "17+ focusedSubmitButton = "[ " + te.String("Submit").Foreground(color("205")).String() + " ]"18+ blurredSubmitButton = "[ " + te.String("Submit").Foreground(color("240")).String() + " ]"19+)20+21+func main() {22+ if err := boba.NewProgram(23+ initialize,24+ update,25+ view,26+ subscriptions,27+ ).Start(); err != nil {28+ fmt.Printf("could not start program: %s\n", err)29+ os.Exit(1)30+ }31+}32+33+type Model struct {34+ index int35+ nameInput input.Model36+ nickNameInput input.Model37+ emailInput input.Model38+ submitButton string39+}40+41+func initialize() (boba.Model, boba.Cmd) {42+ name := input.NewModel()43+ name.Placeholder = "Name"44+ name.Focus()45+ name.Prompt = focusedPrompt46+ name.TextColor = focusedText47+48+ nickName := input.NewModel()49+ nickName.Placeholder = "Nickname"50+ nickName.Prompt = blurredPrompt51+52+ email := input.NewModel()53+ email.Placeholder = "Email"54+ email.Prompt = blurredPrompt55+56+ return Model{0, name, nickName, email, blurredSubmitButton}, nil57+}58+59+func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {60+ m, ok := model.(Model)61+ if !ok {62+ panic("could not perform assertion on model")63+ }64+65+ switch msg := msg.(type) {66+67+ case boba.KeyMsg:68+ switch msg.String() {69+70+ case "ctrl+c":71+ return m, boba.Quit72+73+ // Cycle between inputs74+ case "tab":75+ fallthrough76+ case "shift+tab":77+ fallthrough78+ case "enter":79+ fallthrough80+ case "up":81+ fallthrough82+ case "down":83+ inputs := []input.Model{84+ m.nameInput,85+ m.nickNameInput,86+ m.emailInput,87+ }88+89+ s := msg.String()90+91+ // Did the user press enter while the submit button was focused?92+ // If so, exit.93+ if s == "enter" && m.index == len(inputs) {94+ return m, boba.Quit95+ }96+97+ // Cycle indexes98+ if s == "up" || s == "shift+tab" {99+ m.index--100+ } else {101+ m.index++102+ }103+104+ if m.index > len(inputs) {105+ m.index = 0106+ } else if m.index < 0 {107+ m.index = len(inputs)108+ }109+110+ for i := 0; i <= len(inputs)-1; i++ {111+ if i == m.index {112+ // Focused input113+ inputs[i].Focus()114+ inputs[i].Prompt = focusedPrompt115+ inputs[i].TextColor = focusedText116+ continue117+ }118+ // Blurred input119+ inputs[i].Blur()120+ inputs[i].Prompt = blurredPrompt121+ inputs[i].TextColor = ""122+ }123+124+ m.nameInput = inputs[0]125+ m.nickNameInput = inputs[1]126+ m.emailInput = inputs[2]127+128+ if m.index == len(inputs) {129+ m.submitButton = focusedSubmitButton130+ } else {131+ m.submitButton = blurredSubmitButton132+ }133+134+ return m, nil135+136+ default:137+ // Handle character input138+ m = updateInputs(msg, m)139+ return m, nil140+ }141+142+ default:143+ // Handle blinks144+ m = updateInputs(msg, m)145+ return m, nil146+ }147+}148+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 m154+}155+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+178+func view(model boba.Model) string {179+ m, ok := model.(Model)180+ if !ok {181+ return "[error] could not perform assertion on model"182+ }183+184+ s := "\n"185+186+ inputs := []string{187+ input.View(m.nameInput),188+ input.View(m.nickNameInput),189+ input.View(m.emailInput),190+ }191+192+ for i := 0; i < len(inputs); i++ {193+ s += inputs[i]194+ if i < len(inputs)-1 {195+ s += "\n"196+ }197+ }198+199+ s += "\n\n" + m.submitButton + "\n"200+201+ return s202+}modified:examples/views/main.go+22 added-22 removed
6 unmodified lines7 "math"8 "strings"9 "time"10 11- "github.com/charmbracelet/tea"11+ "github.com/charmbracelet/boba"12 "github.com/fogleman/ease"13 )14 15 func main() {16- p := tea.NewProgram(16+ p := boba.NewProgram(17 initialize,18 update,19 view,20 subscriptions,6 unmodified lines27 // MSG28 29 type tickMsg time.Time30 31-func newTickMsg(t time.Time) tea.Msg {31+func newTickMsg(t time.Time) boba.Msg {32 return tickMsg(t)33 }34 35 type frameMsg time.Time36 37-func newFrameMsg(t time.Time) tea.Msg {37+func newFrameMsg(t time.Time) boba.Msg {38 return frameMsg(t)39 }40 41 // MODEL9 unmodified lines51 }52 53 // INIT54 55-func initialize() (tea.Model, tea.Cmd) {55+func initialize() (boba.Model, boba.Cmd) {56 return Model{0, false, 10, 0, 0, false}, nil57 }58 59 // SUBSCRIPTIONS60 61-func subscriptions(model tea.Model) tea.Subs {61+func subscriptions(model boba.Model) boba.Subs {62 m, _ := model.(Model)63 if !m.Chosen || m.Loaded {64- return tea.Subs{65- "tick": tea.Every(time.Second, newTickMsg),64+ return boba.Subs{65+ "tick": boba.Every(time.Second, newTickMsg),66 }67 }68- return tea.Subs{69- "frame": tea.Every(time.Second/60, newFrameMsg),68+ return boba.Subs{69+ "frame": boba.Every(time.Second/60, newFrameMsg),70 }71 }72 73 // UPDATE74 75-func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {75+func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {76 m, _ := model.(Model)77 78 if !m.Chosen {79 return updateChoices(msg, m)80 }81 return updateChosen(msg, m)82 }83 84-func updateChoices(msg tea.Msg, m Model) (tea.Model, tea.Cmd) {84+func updateChoices(msg boba.Msg, m Model) (boba.Model, boba.Cmd) {85 switch msg := msg.(type) {86 87- case tea.KeyMsg:87+ case boba.KeyMsg:88 switch msg.String() {89 case "j":90 fallthrough91 case "down":15 unmodified lines107 fallthrough108 case "esc":109 fallthrough110 case "ctrl+c":111- return m, tea.Quit111+ return m, boba.Quit112 }113 114 case tickMsg:115 if m.Ticks == 0 {116- return m, tea.Quit116+ return m, boba.Quit117 }118 m.Ticks -= 1119 }120 121 return m, nil122 }123 124-func updateChosen(msg tea.Msg, m Model) (tea.Model, tea.Cmd) {124+func updateChosen(msg boba.Msg, m Model) (boba.Model, boba.Cmd) {125 switch msg := msg.(type) {126 127- case tea.KeyMsg:127+ case boba.KeyMsg:128 switch msg.String() {129 case "q":130 fallthrough131 case "esc":132 fallthrough133 case "ctrl+c":134- return m, tea.Quit134+ return m, boba.Quit135 }136 137 case frameMsg:138 if !m.Loaded {8 unmodified lines147 148 case tickMsg:149 if m.Loaded {150 if m.Ticks == 0 {151- return m, tea.Quit151+ return m, boba.Quit152 }153 m.Ticks -= 1154 }155 }2 unmodified lines158 }159 160 // VIEW161 162-func view(model tea.Model) string {162+func view(model boba.Model) string {163 m, _ := model.(Model)164 if !m.Chosen {165- return choicesView(m)165+ return choicesView(m) + "\n"166 }167- return chosenView(m)167+ return chosenView(m) + "\n"168 }169 170 const choicesTpl = `What to do today?171 59 unmodified linesmodified:examples/go.mod+2 added-2 removed
4 unmodified lines5 replace github.com/charmbracelet/boba => ../6 7 require (8 github.com/charmbracelet/boba v0.0.0-00010101000000-0000000000009- github.com/charmbracelet/tea v0.3.010- github.com/charmbracelet/teaparty v0.0.0-20200511213328-a72bf9128d839 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf177610 github.com/muesli/termenv v0.5.211+ golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 // indirect12+ golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f // indirect13 )modified:examples/go.sum+7 added-12 removed
1-github.com/charmbracelet/tea v0.0.0-20200130023737-bb06373836b4 h1:O8IGyYrKQuCwZZ98JP3DvzQCoPiXM5Y2zjwlDY7mOFM=2-github.com/charmbracelet/tea v0.0.0-20200130023737-bb06373836b4/go.mod h1:UsFFdg04MNbcYi1r2FBtdDEFY07bObaYDKHhE1xZUaQ=3-github.com/charmbracelet/tea v0.3.0 h1:W5F1x/IYeSCKpZl3/hM3Mn5v2KAagckabDFhhzh5sIE=4-github.com/charmbracelet/tea v0.3.0/go.mod h1:uA/DUzCuyIZ1NFyAdCz6k+gF8lspujo6ZvoavcSsLCM=5-github.com/charmbracelet/teaparty v0.0.0-20200212224515-b4d35fd52906 h1:kcvv+hjb0dJiqhtMXkql5tczxalWMPvKIqwWo7cyhiQ=6-github.com/charmbracelet/teaparty v0.0.0-20200212224515-b4d35fd52906/go.mod h1:BG6oiwNZL9hB739ZOifRi3ePRGv0nT+kRTfxYLcZj/Y=7-github.com/charmbracelet/teaparty v0.0.0-20200511213328-a72bf9128d83 h1:ivIS4ze0LLG9yl9L8cnYerh6dWnqhmBqh1ohmrA3I/I=8-github.com/charmbracelet/teaparty v0.0.0-20200511213328-a72bf9128d83/go.mod h1:rlnGPwUokLHs2rQBiIYg6fpLM5m4DvtE2LwzdvS1wsk=1 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=2 github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=3 github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=4 github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=5 github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=6 github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7 github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=8 github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=17-github.com/muesli/termenv v0.4.0/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=9 github.com/muesli/termenv v0.5.2 h1:N1Y1dHRtx6OizOgaIQXd8SkJl4T/cCOV+YyWXiuLUEA=10 github.com/muesli/termenv v0.5.2/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=11 github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942 h1:A7GG7zcGjl3jqAqGPmcNjd/D9hzL95SuoOQAaFNdLU0=12 github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ=13+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=14+golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=15+golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=16+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=17+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=18+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=19 golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=23-golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=24-golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 h1:1/DFK4b7JH8DmkqhUk48onnSfrPzImPoVxuomtbT2nk=25-golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=20 golang.org/x/sys v0.0.0-20200430202703-d923437fa56d h1:xmcims+WSpFuY56YEzkKF6IMDxYAVDRipkQRJfXUBZk=21 golang.org/x/sys v0.0.0-20200430202703-d923437fa56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=22 golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f h1:mOhmO9WsBaJCNmaZHPtHs9wOcdqdKCjF6OPJlmDM3KI=23 golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=24+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=added:pager/pager.go+202 added
1+package pager2+3+import (4+ "errors"5+ "os"6+ "strings"7+8+ "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+21+// MSG22+23+type terminalSizeMsg struct {24+ width int25+ height int26+}27+28+type errMsg error29+30+// MODEL31+32+type State int33+34+const (35+ StateInit State = iota36+ StateReady37+)38+39+type Model struct {40+ Err error41+ Standalone bool42+ State State43+ Width int44+ Height int45+ Y int46+47+ lines []string48+}49+50+// Content adds text content to the model51+func (m *Model) Content(s string) {52+ s = strings.TrimSpace(s)53+ s = strings.Replace(s, "\r\n", "\n", -1) // normalize line endings54+ m.lines = strings.Split(s, "\n")55+}56+57+func NewModel() Model {58+ return Model{59+ State: StateInit,60+ }61+}62+63+// INIT64+65+func Init(initialContent string) func() (boba.Model, boba.Cmd) {66+ m := NewModel()67+ m.Standalone = true68+ m.Content(initialContent)69+ return func() (boba.Model, boba.Cmd) {70+ return m, getTerminalSize71+ }72+}73+74+// UPDATE75+76+func Update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {77+ m, ok := model.(Model)78+ if !ok {79+ return Model{80+ Err: errors.New("could not perform assertion on model in update in pager; are you sure you passed the correct model?"),81+ }, nil82+ }83+84+ switch msg := msg.(type) {85+86+ case boba.KeyMsg:87+ switch msg.String() {88+ case "q":89+ fallthrough90+ case "ctrl+c":91+ if m.Standalone {92+ return m, boba.Quit93+ }94+95+ // Up one page96+ case "b":97+ m.Y = max(0, m.Y-m.Height)98+ return m, nil99+100+ // Down one page101+ case "space":102+ fallthrough103+ case "f":104+ m.Y = min(len(m.lines)-m.Height, m.Y+m.Height)105+ return m, nil106+107+ // Up half page108+ case "u":109+ m.Y = max(0, m.Y-m.Height/2)110+ return m, nil111+112+ // Down half page113+ case "d":114+ m.Y = min(len(m.lines)-m.Height, m.Y+m.Height/2)115+ return m, nil116+117+ // Up one line118+ case "up":119+ fallthrough120+ case "k":121+ m.Y = max(0, m.Y-1)122+ return m, nil123+124+ // Down one line125+ case "down":126+ fallthrough127+ case "j":128+ m.Y = min(len(m.lines)-m.Height, m.Y+1)129+ return m, nil130+131+ // Re-render132+ case "ctrl+l":133+ return m, getTerminalSize134+135+ }136+137+ case errMsg:138+ m.Err = msg139+ return m, nil140+141+ case terminalSizeMsg:142+ m.Width = msg.width143+ m.Height = msg.height144+ m.State = StateReady145+ return m, nil146+ }147+148+ return model, nil149+}150+151+// VIEW152+153+func View(model boba.Model) string {154+ m, ok := model.(Model)155+ if !ok {156+ return "could not perform assertion on model in view in pager; are you sure you passed the correct model?"157+ }158+159+ if m.Err != nil {160+ return m.Err.Error()161+ }162+163+ if len(m.lines) == 0 {164+ return "(Buffer empty)"165+ }166+167+ if m.State == StateReady {168+ // Render viewport169+ top := max(0, m.Y)170+ bottom := min(len(m.lines), m.Y+m.Height)171+ lines := m.lines[top:bottom]172+ return "\n" + strings.Join(lines, "\n")173+ }174+175+ return ""176+}177+178+// CMD179+180+func getTerminalSize() boba.Msg {181+ w, h, err := terminal.GetSize(int(os.Stdout.Fd()))182+ if err != nil {183+ return errMsg(err)184+ }185+ return terminalSizeMsg{w, h}186+}187+188+// ETC189+190+func min(a, b int) int {191+ if a < b {192+ return a193+ }194+ return b195+}196+197+func max(a, b int) int {198+ if a > b {199+ return a200+ }201+ return b202+}added:paginator/paginator.go+183 added
1+// package paginator provides a Boba package for calulating pagination and2+// rendering pagination info. Note that this package does not render actual3+// pages: it's purely for handling keystrokes related to pagination, and4+// rendering pagination status.5+package paginator6+7+import (8+ "fmt"9+10+ "github.com/charmbracelet/boba"11+)12+13+// PaginatorType specifies the way we render pagination14+type PaginatorType int15+16+// Pagination rendering options17+const (18+ Arabic PaginatorType = iota19+ Dots20+)21+22+// Model is the Boba model for this user interface23+type Model struct {24+ Type PaginatorType25+ Page int26+ PerPage int27+ TotalPages int28+ ActiveDot string29+ InactiveDot string30+ ArabicFormat string31+ UseLeftRightKeys bool32+ UseUpDownKeys bool33+ UseHLKeys bool34+ UseJKKeys bool35+}36+37+// SetTotalPages is a helper function for calculatng the total number of pages38+// from a given number of items. It's use is optional since this pager can be39+// used for other things beyond navigating sets. Note that it both returns the40+// number of total pages and alters the model.41+func (m *Model) SetTotalPages(items int) int {42+ if items == 0 {43+ return 044+ }45+ n := items / m.PerPage46+ if items%m.PerPage > 0 {47+ n += 148+ }49+ m.TotalPages = n50+ return n51+}52+53+// ItemsOnPage is a helper function fro returning the numer of items on the54+// current page given the total numer of items passed as an argument.55+func (m Model) ItemsOnPage(totalItems int) int {56+ start, end := m.GetSliceBounds(totalItems)57+ return end - start58+}59+60+// GetSliceBounds is a helper function for paginating slices. Pass the length61+// of the slice you're rendering and you'll receive the start and end bounds62+// corresponding the to pagination. For example:63+//64+// bunchOfStuff := []stuff{...}65+// start, end := model.GetSliceBounds(len(bunchOfStuff))66+// sliceToRender := bunchOfStuff[start:end]67+//68+func (m *Model) GetSliceBounds(length int) (start int, end int) {69+ start = m.Page * m.PerPage70+ end = min(m.Page*m.PerPage+m.PerPage, length)71+ return start, end72+}73+74+// PrevPage is a number function for navigating one page backward. It will not75+// page beyond the first page (i.e. page 0).76+func (m *Model) PrevPage() {77+ if m.Page > 0 {78+ m.Page--79+ }80+}81+82+// NextPage is a helper function for navigating one page forward. It will not83+// page beyond the last page (i.e. totalPages - 1).84+func (m *Model) NextPage() {85+ if m.Page < m.TotalPages-1 {86+ m.Page++87+ }88+}89+90+// NewModel creates a new model with defaults91+func NewModel() Model {92+ return Model{93+ Type: Arabic,94+ Page: 0,95+ PerPage: 1,96+ TotalPages: 1,97+ ActiveDot: "•",98+ InactiveDot: "○",99+ ArabicFormat: "%d/%d",100+ UseLeftRightKeys: true,101+ UseUpDownKeys: false,102+ UseHLKeys: true,103+ UseJKKeys: false,104+ }105+}106+107+// Update is the Boba update function which binds keystrokes to pagination108+func Update(msg boba.Msg, m Model) (Model, boba.Cmd) {109+ switch msg := msg.(type) {110+ case boba.KeyMsg:111+ if m.UseLeftRightKeys {112+ switch msg.String() {113+ case "left":114+ m.PrevPage()115+ case "right":116+ m.NextPage()117+ }118+ }119+ if m.UseUpDownKeys {120+ switch msg.String() {121+ case "up":122+ m.PrevPage()123+ case "down":124+ m.NextPage()125+ }126+ }127+ if m.UseHLKeys {128+ switch msg.String() {129+ case "h":130+ m.PrevPage()131+ case "l":132+ m.NextPage()133+ }134+ }135+ if m.UseJKKeys {136+ switch msg.String() {137+ case "j":138+ m.PrevPage()139+ case "k":140+ m.NextPage()141+ }142+ }143+ }144+145+ return m, nil146+}147+148+// View renders the pagination to a string149+func View(model boba.Model) string {150+ m, ok := model.(Model)151+ if !ok {152+ return "could not perform assertion on model"153+ }154+ switch m.Type {155+ case Dots:156+ return dotsView(m)157+ default:158+ return arabicView(m)159+ }160+}161+162+func dotsView(m Model) string {163+ var s string164+ for i := 0; i < m.TotalPages; i++ {165+ if i == m.Page {166+ s += m.ActiveDot167+ continue168+ }169+ s += m.InactiveDot170+ }171+ return s172+}173+174+func arabicView(m Model) string {175+ return fmt.Sprintf(m.ArabicFormat, m.Page+1, m.TotalPages)176+}177+178+func min(a, b int) int {179+ if a < b {180+ return a181+ }182+ return b183+}added:spinner/spinner.go+100 added
1+package spinner2+3+import (4+ "errors"5+ "time"6+7+ "github.com/charmbracelet/boba"8+ "github.com/muesli/termenv"9+)10+11+// Spinner denotes a type of spinner12+type Spinner = int13+14+// Available types of spinners15+const (16+ Line Spinner = iota17+ Dot18+)19+20+var (21+ // Spinner frames22+ spinners = map[Spinner][]string{23+ Line: {"|", "/", "-", "\\"},24+ Dot: {"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},25+ }26+27+ assertionErr = errors.New("could not perform assertion on model to what the spinner expects. are you sure you passed the right value?")28+29+ color = termenv.ColorProfile().Color30+)31+32+// Model contains the state for the spinner. Use NewModel to create new models33+// rather than using Model as a struct literal.34+type Model struct {35+ Type Spinner36+ FPS int37+ ForegroundColor string38+ BackgroundColor string39+40+ frame int41+}42+43+// NewModel returns a model with default values44+func NewModel() Model {45+ return Model{46+ Type: Line,47+ FPS: 9,48+ frame: 0,49+ }50+}51+52+// TickMsg indicates that the timer has ticked and we should render a frame53+type TickMsg time.Time54+55+// Update is the Boba update function56+func Update(msg boba.Msg, m Model) (Model, boba.Cmd) {57+ switch msg.(type) {58+ case TickMsg:59+ m.frame++60+ if m.frame >= len(spinners[m.Type]) {61+ m.frame = 062+ }63+ return m, nil64+ default:65+ return m, nil66+ }67+}68+69+// View renders the model's view70+func View(model Model) string {71+ s := spinners[model.Type]72+ if model.frame >= len(s) {73+ return "[error]"74+ }75+76+ str := s[model.frame]77+78+ if model.ForegroundColor != "" || model.BackgroundColor != "" {79+ return termenv.80+ String(str).81+ Foreground(color(model.ForegroundColor)).82+ Background(color(model.BackgroundColor)).83+ String()84+ }85+86+ return str87+}88+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, assertionErr96+ }97+ return boba.Tick(time.Second/time.Duration(m.FPS), func(t time.Time) boba.Msg {98+ return TickMsg(t)99+ }), nil100+}added:textinput/textinput.go+244 added
1+package textinput2+3+import (4+ "errors"5+ "time"6+7+ "github.com/charmbracelet/boba"8+ "github.com/muesli/termenv"9+)10+11+var (12+ // color is a helper for returning colors13+ color func(s string) termenv.Color = termenv.ColorProfile().Color14+)15+16+// ErrMsg indicates there's been an error. We don't handle errors in the this17+// package; we're expecting errors to be handle in the program that implements18+// this text input.19+type ErrMsg error20+21+// Model is the Boba model for this text input element22+type Model struct {23+ Err error24+ Prompt string25+ Value string26+ Cursor string27+ BlinkSpeed time.Duration28+ Placeholder string29+ TextColor string30+ PlaceholderColor string31+ CursorColor string32+33+ // CharLimit is the maximum amount of characters this input element will34+ // accept. If 0 or less, there's no limit.35+ CharLimit int36+37+ // Focus indicates whether user input focus should be on this input38+ // component. When false, don't blink and ignore keyboard input.39+ focus bool40+41+ blink bool42+ pos int43+}44+45+// Focused returns the focus state on the model46+func (m Model) Focused() bool {47+ return m.focus48+}49+50+// Focus sets the focus state on the model51+func (m *Model) Focus() {52+ m.focus = true53+ m.blink = false54+}55+56+// Blur removes the focus state on the model57+func (m *Model) Blur() {58+ m.focus = false59+ m.blink = true60+}61+62+// colorText colorizes a given string according to the TextColor value of the63+// model64+func (m *Model) colorText(s string) string {65+ return termenv.66+ String(s).67+ Foreground(color(m.TextColor)).68+ String()69+}70+71+// colorPlaceholder colorizes a given string according to the TextColor value72+// of the model73+func (m *Model) colorPlaceholder(s string) string {74+ return termenv.75+ String(s).76+ Foreground(color(m.PlaceholderColor)).77+ String()78+}79+80+// CursorBlinkMsg is sent when the cursor should alternate it's blinking state81+type CursorBlinkMsg struct{}82+83+// NewModel creates a new model with default settings84+func NewModel() Model {85+ return Model{86+ Prompt: "> ",87+ Value: "",88+ BlinkSpeed: time.Millisecond * 600,89+ Placeholder: "",90+ TextColor: "",91+ PlaceholderColor: "240",92+ CursorColor: "",93+ CharLimit: 0,94+95+ focus: false,96+ blink: true,97+ pos: 0,98+ }99+}100+101+// Update is the Boba update loop102+func Update(msg boba.Msg, m Model) (Model, boba.Cmd) {103+ if !m.focus {104+ m.blink = true105+ return m, nil106+ }107+108+ switch msg := msg.(type) {109+110+ case boba.KeyMsg:111+ switch msg.Type {112+ case boba.KeyBackspace:113+ fallthrough114+ case boba.KeyDelete:115+ if len(m.Value) > 0 {116+ m.Value = m.Value[:m.pos-1] + m.Value[m.pos:]117+ m.pos--118+ }119+ return m, nil120+ case boba.KeyLeft:121+ if m.pos > 0 {122+ m.pos--123+ }124+ return m, nil125+ case boba.KeyRight:126+ if m.pos < len(m.Value) {127+ m.pos++128+ }129+ return m, nil130+ case boba.KeyCtrlF: // ^F, forward one character131+ fallthrough132+ case boba.KeyCtrlB: // ^B, back one charcter133+ fallthrough134+ case boba.KeyCtrlA: // ^A, go to beginning135+ m.pos = 0136+ return m, nil137+ case boba.KeyCtrlD: // ^D, delete char under cursor138+ if len(m.Value) > 0 && m.pos < len(m.Value) {139+ m.Value = m.Value[:m.pos] + m.Value[m.pos+1:]140+ }141+ return m, nil142+ case boba.KeyCtrlE: // ^E, go to end143+ m.pos = len(m.Value)144+ return m, nil145+ case boba.KeyCtrlK: // ^K, kill text after cursor146+ m.Value = m.Value[:m.pos]147+ m.pos = len(m.Value)148+ return m, nil149+ case boba.KeyCtrlU: // ^U, kill text before cursor150+ m.Value = m.Value[m.pos:]151+ m.pos = 0152+ return m, nil153+ case boba.KeyRune: // input a regular character154+ if m.CharLimit <= 0 || len(m.Value) < m.CharLimit {155+ m.Value = m.Value[:m.pos] + string(msg.Rune) + m.Value[m.pos:]156+ m.pos++157+ }158+ return m, nil159+ default:160+ return m, nil161+ }162+163+ case ErrMsg:164+ m.Err = msg165+ return m, nil166+167+ case CursorBlinkMsg:168+ m.blink = !m.blink169+ return m, nil170+171+ default:172+ return m, nil173+ }174+}175+176+// View renders the textinput in its current state177+func View(model boba.Model) string {178+ m, ok := model.(Model)179+ if !ok {180+ return "could not perform assertion on model"181+ }182+183+ // Placeholder text184+ if m.Value == "" && m.Placeholder != "" {185+ return placeholderView(m)186+ }187+188+ v := m.colorText(m.Value[:m.pos])189+190+ if m.pos < len(m.Value) {191+ v += cursorView(string(m.Value[m.pos]), m)192+ v += m.colorText(m.Value[m.pos+1:])193+ } else {194+ v += cursorView(" ", m)195+ }196+ return m.Prompt + v197+}198+199+// placeholderView200+func placeholderView(m Model) string {201+ var (202+ v string203+ p = m.Placeholder204+ )205+206+ // Cursor207+ if m.blink && m.PlaceholderColor != "" {208+ v += cursorView(209+ m.colorPlaceholder(p[:1]),210+ m,211+ )212+ } else {213+ v += cursorView(p[:1], m)214+ }215+216+ // The rest of the placeholder text217+ v += m.colorPlaceholder(p[1:])218+219+ return m.Prompt + v220+}221+222+// cursorView style the cursor223+func cursorView(s string, m Model) string {224+ if m.blink {225+ return s226+ }227+ return termenv.String(s).228+ Foreground(color(m.CursorColor)).229+ Reverse().230+ String()231+}232+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+ }240+ return func() boba.Msg {241+ time.Sleep(m.BlinkSpeed)242+ return CursorBlinkMsg{}243+ }, nil244+}modified:go.mod+1 added
3 unmodified lines4 5 require (6 github.com/muesli/termenv v0.5.27 github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e9428+ golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e379 golang.org/x/sys v0.0.0-20200430202703-d923437fa56d // indirect10 )modified:go.sum+7 added
6 unmodified lines7 github.com/muesli/termenv v0.5.2 h1:N1Y1dHRtx6OizOgaIQXd8SkJl4T/cCOV+YyWXiuLUEA=8 github.com/muesli/termenv v0.5.2/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=9 github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942 h1:A7GG7zcGjl3jqAqGPmcNjd/D9hzL95SuoOQAaFNdLU0=10 github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ=11+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=12+golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=13+golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=14+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=15+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=16+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=17 golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=18 golang.org/x/sys v0.0.0-20200430202703-d923437fa56d h1:xmcims+WSpFuY56YEzkKF6IMDxYAVDRipkQRJfXUBZk=19 golang.org/x/sys v0.0.0-20200430202703-d923437fa56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=20+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=