Skip to content
Myr

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

15 files+1002 added−57 removed

modified:examples/http/main.go+1 added-1 removed
72 unmodified lines
73 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}7980func checkServer() boba.Msg {81 c := &http.Client{
8 unmodified lines
modified:examples/input/main.go+15 added-11 removed
1package main23// A simple program that counts down from 5 and then exits.43import (4 "errors"5 "fmt"6 "log"78 "github.com/charmbracelet/boba"11 "github.com/charmbracelet/teaparty/input"9 input "github.com/charmbracelet/boba/textinput"10)1112type Model struct {13 textInput input.Model
16 unmodified lines
30 }31}3233func initialize() (boba.Model, boba.Cmd) {36 inputModel := input.DefaultModel()34 inputModel := input.NewModel()35 inputModel.Placeholder = "Pikachu"36 inputModel.Focus()3738 return Model{39 textInput: inputModel,40 err: nil,
17 unmodified lines
58 switch msg.Type {59 case boba.KeyCtrlC:60 fallthrough61 case boba.KeyEsc:62 fallthrough63 case boba.KeyEnter:64 return m, boba.Quit65 }6667 // We handle errors just like any other message
6 unmodified lines
74 return m, cmd75}7677func 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}9091func view(model boba.Model) string {
6 unmodified lines
98 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 lines
5 "io/ioutil"6 "os"78 "github.com/charmbracelet/boba"9 "github.com/charmbracelet/teaparty/pager"9 "github.com/charmbracelet/boba/pager"10)1112func main() {13 content, err := ioutil.ReadFile("artichoke.md")
12 unmodified lines
modified:examples/simple/main.go+1 added-1 removed
52 unmodified lines
53// Views take data from the model and return a string which will be rendered54// to the terminal.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)57 return fmt.Sprintf("Hi. This program will exit in %d seconds. To quit sooner press any key.\n", m)58}5960// This is a subscription which we setup in NewProgram(). It waits for one61// second, sends a tick, and then restarts.
7 unmodified lines
modified:examples/spinner/main.go+14 added-7 removed
1package main23import (4 "fmt"5 "log"5 "os"67 "github.com/charmbracelet/boba"8 "github.com/charmbracelet/teaparty/spinner"8 "github.com/charmbracelet/boba/spinner"9 "github.com/muesli/termenv"10)1112var (13 color = termenv.ColorProfile()14)1516type Model struct {17 spinner spinner.Model18 err error17 spinner spinner.Model18 quitting bool19 err error20}2122type errMsg error2324func 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}3132func initialize() (boba.Model, boba.Cmd) {
19 unmodified lines
52 fallthrough53 case "esc":54 fallthrough55 case "ctrl+c":56 m.quitting = true57 return m, boba.Quit58 default:59 return m, nil60 }
11 unmodified lines
7273func 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}9192func subscriptions(model boba.Model) boba.Subs {93 m, ok := model.(Model)
12 unmodified lines
added:examples/textinputs/main.go+202 added
1package main23import (4 "fmt"5 "os"67 "github.com/charmbracelet/boba"8 input "github.com/charmbracelet/boba/textinput"9 te "github.com/muesli/termenv"10)1112var (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)2021func 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}3233type Model struct {34 index int35 nameInput input.Model36 nickNameInput input.Model37 emailInput input.Model38 submitButton string39}4041func initialize() (boba.Model, boba.Cmd) {42 name := input.NewModel()43 name.Placeholder = "Name"44 name.Focus()45 name.Prompt = focusedPrompt46 name.TextColor = focusedText4748 nickName := input.NewModel()49 nickName.Placeholder = "Nickname"50 nickName.Prompt = blurredPrompt5152 email := input.NewModel()53 email.Placeholder = "Email"54 email.Prompt = blurredPrompt5556 return Model{0, name, nickName, email, blurredSubmitButton}, nil57}5859func 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 }6465 switch msg := msg.(type) {6667 case boba.KeyMsg:68 switch msg.String() {6970 case "ctrl+c":71 return m, boba.Quit7273 // 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 }8889 s := msg.String()9091 // 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 }9697 // Cycle indexes98 if s == "up" || s == "shift+tab" {99 m.index--100 } else {101 m.index++102 }103104 if m.index > len(inputs) {105 m.index = 0106 } else if m.index < 0 {107 m.index = len(inputs)108 }109110 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 }123124 m.nameInput = inputs[0]125 m.nickNameInput = inputs[1]126 m.emailInput = inputs[2]127128 if m.index == len(inputs) {129 m.submitButton = focusedSubmitButton130 } else {131 m.submitButton = blurredSubmitButton132 }133134 return m, nil135136 default:137 // Handle character input138 m = updateInputs(msg, m)139 return m, nil140 }141142 default:143 // Handle blinks144 m = updateInputs(msg, m)145 return m, nil146 }147}148149func 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}155156func 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}177178func view(model boba.Model) string {179 m, ok := model.(Model)180 if !ok {181 return "[error] could not perform assertion on model"182 }183184 s := "\n"185186 inputs := []string{187 input.View(m.nameInput),188 input.View(m.nickNameInput),189 input.View(m.emailInput),190 }191192 for i := 0; i < len(inputs); i++ {193 s += inputs[i]194 if i < len(inputs)-1 {195 s += "\n"196 }197 }198199 s += "\n\n" + m.submitButton + "\n"200201 return s202}
modified:examples/views/main.go+22 added-22 removed
6 unmodified lines
7 "math"8 "strings"9 "time"1011 "github.com/charmbracelet/tea"11 "github.com/charmbracelet/boba"12 "github.com/fogleman/ease"13)1415func main() {16 p := tea.NewProgram(16 p := boba.NewProgram(17 initialize,18 update,19 view,20 subscriptions,
6 unmodified lines
27// MSG2829type tickMsg time.Time3031func newTickMsg(t time.Time) tea.Msg {31func newTickMsg(t time.Time) boba.Msg {32 return tickMsg(t)33}3435type frameMsg time.Time3637func newFrameMsg(t time.Time) tea.Msg {37func newFrameMsg(t time.Time) boba.Msg {38 return frameMsg(t)39}4041// MODEL
9 unmodified lines
51}5253// INIT5455func initialize() (tea.Model, tea.Cmd) {55func initialize() (boba.Model, boba.Cmd) {56 return Model{0, false, 10, 0, 0, false}, nil57}5859// SUBSCRIPTIONS6061func subscriptions(model tea.Model) tea.Subs {61func 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}7273// UPDATE7475func update(msg tea.Msg, model tea.Model) (tea.Model, tea.Cmd) {75func update(msg boba.Msg, model boba.Model) (boba.Model, boba.Cmd) {76 m, _ := model.(Model)7778 if !m.Chosen {79 return updateChoices(msg, m)80 }81 return updateChosen(msg, m)82}8384func updateChoices(msg tea.Msg, m Model) (tea.Model, tea.Cmd) {84func updateChoices(msg boba.Msg, m Model) (boba.Model, boba.Cmd) {85 switch msg := msg.(type) {8687 case tea.KeyMsg:87 case boba.KeyMsg:88 switch msg.String() {89 case "j":90 fallthrough91 case "down":
15 unmodified lines
107 fallthrough108 case "esc":109 fallthrough110 case "ctrl+c":111 return m, tea.Quit111 return m, boba.Quit112 }113114 case tickMsg:115 if m.Ticks == 0 {116 return m, tea.Quit116 return m, boba.Quit117 }118 m.Ticks -= 1119 }120121 return m, nil122}123124func updateChosen(msg tea.Msg, m Model) (tea.Model, tea.Cmd) {124func updateChosen(msg boba.Msg, m Model) (boba.Model, boba.Cmd) {125 switch msg := msg.(type) {126127 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 }136137 case frameMsg:138 if !m.Loaded {
8 unmodified lines
147148 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 lines
158}159160// VIEW161162func view(model tea.Model) string {162func 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}169170const choicesTpl = `What to do today?171
59 unmodified lines
modified:examples/go.mod+2 added-2 removed
4 unmodified lines
5replace github.com/charmbracelet/boba => ../67require (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
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=1github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776 h1:VRIbnDWRmAh5yBdz+J6yFMF5vso1It6vn+WmM/5l7MA=2github.com/fogleman/ease v0.0.0-20170301025033-8da417bf1776/go.mod h1:9wvnDu3YOfxzWM9Cst40msBF1C2UdQgDv962oTxSuMs=3github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f h1:5CjVwnuUcp5adK4gmY6i72gpVFVnZDP2h5TmPScB6u4=4github.com/google/goterm v0.0.0-20190703233501-fc88cf888a3f/go.mod h1:nOFQdrUlIlx6M6ODdSpBj1NVA+VgLC6kmw60mkw34H4=5github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=6github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=7github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=8github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=17github.com/muesli/termenv v0.4.0/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=9github.com/muesli/termenv v0.5.2 h1:N1Y1dHRtx6OizOgaIQXd8SkJl4T/cCOV+YyWXiuLUEA=10github.com/muesli/termenv v0.5.2/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=11github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942 h1:A7GG7zcGjl3jqAqGPmcNjd/D9hzL95SuoOQAaFNdLU0=12github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ=13golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=14golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=15golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=16golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=17golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=18golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=19golang.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=20golang.org/x/sys v0.0.0-20200430202703-d923437fa56d h1:xmcims+WSpFuY56YEzkKF6IMDxYAVDRipkQRJfXUBZk=21golang.org/x/sys v0.0.0-20200430202703-d923437fa56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=22golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f h1:mOhmO9WsBaJCNmaZHPtHs9wOcdqdKCjF6OPJlmDM3KI=23golang.org/x/sys v0.0.0-20200509044756-6aff5f38e54f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=24golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
added:pager/pager.go+202 added
1package pager23import (4 "errors"5 "os"6 "strings"78 "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}2021// MSG2223type terminalSizeMsg struct {24 width int25 height int26}2728type errMsg error2930// MODEL3132type State int3334const (35 StateInit State = iota36 StateReady37)3839type Model struct {40 Err error41 Standalone bool42 State State43 Width int44 Height int45 Y int4647 lines []string48}4950// Content adds text content to the model51func (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}5657func NewModel() Model {58 return Model{59 State: StateInit,60 }61}6263// INIT6465func 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}7374// UPDATE7576func 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 }8384 switch msg := msg.(type) {8586 case boba.KeyMsg:87 switch msg.String() {88 case "q":89 fallthrough90 case "ctrl+c":91 if m.Standalone {92 return m, boba.Quit93 }9495 // Up one page96 case "b":97 m.Y = max(0, m.Y-m.Height)98 return m, nil99100 // 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, nil106107 // Up half page108 case "u":109 m.Y = max(0, m.Y-m.Height/2)110 return m, nil111112 // Down half page113 case "d":114 m.Y = min(len(m.lines)-m.Height, m.Y+m.Height/2)115 return m, nil116117 // Up one line118 case "up":119 fallthrough120 case "k":121 m.Y = max(0, m.Y-1)122 return m, nil123124 // Down one line125 case "down":126 fallthrough127 case "j":128 m.Y = min(len(m.lines)-m.Height, m.Y+1)129 return m, nil130131 // Re-render132 case "ctrl+l":133 return m, getTerminalSize134135 }136137 case errMsg:138 m.Err = msg139 return m, nil140141 case terminalSizeMsg:142 m.Width = msg.width143 m.Height = msg.height144 m.State = StateReady145 return m, nil146 }147148 return model, nil149}150151// VIEW152153func 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 }158159 if m.Err != nil {160 return m.Err.Error()161 }162163 if len(m.lines) == 0 {164 return "(Buffer empty)"165 }166167 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 }174175 return ""176}177178// CMD179180func 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}187188// ETC189190func min(a, b int) int {191 if a < b {192 return a193 }194 return b195}196197func 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.5package paginator67import (8 "fmt"910 "github.com/charmbracelet/boba"11)1213// PaginatorType specifies the way we render pagination14type PaginatorType int1516// Pagination rendering options17const (18 Arabic PaginatorType = iota19 Dots20)2122// Model is the Boba model for this user interface23type 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}3637// 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.41func (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}5253// 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.55func (m Model) ItemsOnPage(totalItems int) int {56 start, end := m.GetSliceBounds(totalItems)57 return end - start58}5960// 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//68func (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}7374// PrevPage is a number function for navigating one page backward. It will not75// page beyond the first page (i.e. page 0).76func (m *Model) PrevPage() {77 if m.Page > 0 {78 m.Page--79 }80}8182// NextPage is a helper function for navigating one page forward. It will not83// page beyond the last page (i.e. totalPages - 1).84func (m *Model) NextPage() {85 if m.Page < m.TotalPages-1 {86 m.Page++87 }88}8990// NewModel creates a new model with defaults91func 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}106107// Update is the Boba update function which binds keystrokes to pagination108func 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 }144145 return m, nil146}147148// View renders the pagination to a string149func 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}161162func 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}173174func arabicView(m Model) string {175 return fmt.Sprintf(m.ArabicFormat, m.Page+1, m.TotalPages)176}177178func min(a, b int) int {179 if a < b {180 return a181 }182 return b183}
added:spinner/spinner.go+100 added
1package spinner23import (4 "errors"5 "time"67 "github.com/charmbracelet/boba"8 "github.com/muesli/termenv"9)1011// Spinner denotes a type of spinner12type Spinner = int1314// Available types of spinners15const (16 Line Spinner = iota17 Dot18)1920var (21 // Spinner frames22 spinners = map[Spinner][]string{23 Line: {"|", "/", "-", "\\"},24 Dot: {"⣾ ", "⣽ ", "⣻ ", "⢿ ", "⡿ ", "⣟ ", "⣯ ", "⣷ "},25 }2627 assertionErr = errors.New("could not perform assertion on model to what the spinner expects. are you sure you passed the right value?")2829 color = termenv.ColorProfile().Color30)3132// Model contains the state for the spinner. Use NewModel to create new models33// rather than using Model as a struct literal.34type Model struct {35 Type Spinner36 FPS int37 ForegroundColor string38 BackgroundColor string3940 frame int41}4243// NewModel returns a model with default values44func NewModel() Model {45 return Model{46 Type: Line,47 FPS: 9,48 frame: 0,49 }50}5152// TickMsg indicates that the timer has ticked and we should render a frame53type TickMsg time.Time5455// Update is the Boba update function56func 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}6869// View renders the model's view70func View(model Model) string {71 s := spinners[model.Type]72 if model.frame >= len(s) {73 return "[error]"74 }7576 str := s[model.frame]7778 if model.ForegroundColor != "" || model.BackgroundColor != "" {79 return termenv.80 String(str).81 Foreground(color(model.ForegroundColor)).82 Background(color(model.BackgroundColor)).83 String()84 }8586 return str87}8889// 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, 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
1package textinput23import (4 "errors"5 "time"67 "github.com/charmbracelet/boba"8 "github.com/muesli/termenv"9)1011var (12 // color is a helper for returning colors13 color func(s string) termenv.Color = termenv.ColorProfile().Color14)1516// 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.19type ErrMsg error2021// Model is the Boba model for this text input element22type Model struct {23 Err error24 Prompt string25 Value string26 Cursor string27 BlinkSpeed time.Duration28 Placeholder string29 TextColor string30 PlaceholderColor string31 CursorColor string3233 // CharLimit is the maximum amount of characters this input element will34 // accept. If 0 or less, there's no limit.35 CharLimit int3637 // Focus indicates whether user input focus should be on this input38 // component. When false, don't blink and ignore keyboard input.39 focus bool4041 blink bool42 pos int43}4445// Focused returns the focus state on the model46func (m Model) Focused() bool {47 return m.focus48}4950// Focus sets the focus state on the model51func (m *Model) Focus() {52 m.focus = true53 m.blink = false54}5556// Blur removes the focus state on the model57func (m *Model) Blur() {58 m.focus = false59 m.blink = true60}6162// colorText colorizes a given string according to the TextColor value of the63// model64func (m *Model) colorText(s string) string {65 return termenv.66 String(s).67 Foreground(color(m.TextColor)).68 String()69}7071// colorPlaceholder colorizes a given string according to the TextColor value72// of the model73func (m *Model) colorPlaceholder(s string) string {74 return termenv.75 String(s).76 Foreground(color(m.PlaceholderColor)).77 String()78}7980// CursorBlinkMsg is sent when the cursor should alternate it's blinking state81type CursorBlinkMsg struct{}8283// NewModel creates a new model with default settings84func 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,9495 focus: false,96 blink: true,97 pos: 0,98 }99}100101// Update is the Boba update loop102func Update(msg boba.Msg, m Model) (Model, boba.Cmd) {103 if !m.focus {104 m.blink = true105 return m, nil106 }107108 switch msg := msg.(type) {109110 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 }162163 case ErrMsg:164 m.Err = msg165 return m, nil166167 case CursorBlinkMsg:168 m.blink = !m.blink169 return m, nil170171 default:172 return m, nil173 }174}175176// View renders the textinput in its current state177func View(model boba.Model) string {178 m, ok := model.(Model)179 if !ok {180 return "could not perform assertion on model"181 }182183 // Placeholder text184 if m.Value == "" && m.Placeholder != "" {185 return placeholderView(m)186 }187188 v := m.colorText(m.Value[:m.pos])189190 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}198199// placeholderView200func placeholderView(m Model) string {201 var (202 v string203 p = m.Placeholder204 )205206 // 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 }215216 // The rest of the placeholder text217 v += m.colorPlaceholder(p[1:])218219 return m.Prompt + v220}221222// cursorView style the cursor223func 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}232233// 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 }240 return func() boba.Msg {241 time.Sleep(m.BlinkSpeed)242 return CursorBlinkMsg{}243 }, nil244}
modified:go.mod+1 added
3 unmodified lines
45require (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 lines
7github.com/muesli/termenv v0.5.2 h1:N1Y1dHRtx6OizOgaIQXd8SkJl4T/cCOV+YyWXiuLUEA=8github.com/muesli/termenv v0.5.2/go.mod h1:O1/I6sw+6KcrgAmcs6uiUVr7Lui+DNVbHTzt9Lm/PlI=9github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942 h1:A7GG7zcGjl3jqAqGPmcNjd/D9hzL95SuoOQAaFNdLU0=10github.com/pkg/term v0.0.0-20190109203006-aa71e9d9e942/go.mod h1:eCbImbZ95eXtAUIbLAuAVnBnwf83mjf6QIVH8SHYwqQ=11golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=12golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw=13golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=14golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=15golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=16golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=17golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=18golang.org/x/sys v0.0.0-20200430202703-d923437fa56d h1:xmcims+WSpFuY56YEzkKF6IMDxYAVDRipkQRJfXUBZk=19golang.org/x/sys v0.0.0-20200430202703-d923437fa56d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=20golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=