GO语言每日一问

简介
bubbletea是一个简单、小巧、可以非常方便地用来编写 TUI(terminal User Interface,控制台界面程序)程序的框架。内置简单的事件处理机制,可以对外部事件做出响应,如键盘按键。一起来看下吧。先看看bubbletea能做出什么效果:


图片1.png

快速使用
本文代码使用 Go Modules。
创建目录并初始化:
$ mkdir bubbletea && cd bubbletea
$ go mod init github.com/darjun/go-daily-lib/bubbletea
安装bubbletea库:
$ go get -u github.com/charmbracelet/bubbletea
bubbletea程序都需要有一个实现bubbletea.Model接口的类型:
type Model interface {
Init() Cmd
Update(Msg) (Model, Cmd)
View() string
}
Init()方法在程序启动时会立刻调用,它会做一些初始化工作,并返回一个Cmd告诉bubbletea要执行什么命令;
Update()方法用来响应外部事件,返回一个修改后的模型,和想要bubbletea执行的命令;
View()方法用于返回在控制台上显示的文本字符串。
下面我们来实现一个 Todo List。首先定义模型:
type model struct {
todos []string
cursor int
selected map[int]struct{}
}
todos:所有待完成事项;
cursor:界面上光标位置;
selected:已完成标识。
不需要任何初始化工作,实现一个空的Init()方法,并返回nil:
import (

todos:所有待完成事项;
cursor:界面上光标位置;
selected:已完成标识。
我们需要响应按键事件,实现Update()方法。按键事件发生时会以相应的tea.Msg为参数调用Update()方法。通过对参数tea.Msg进行类型断言,我们可以对不同的事件进行对应的处理:
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:

switch msg.String() {
case "ctrl+c", "q":
  return m, tea.Quit

case "up", "k":
  if m.cursor > 0 {
    m.cursor--
  }

case "down", "j":
  if m.cursor < len(m.todos)-1 {
    m.cursor++
  }

case "enter", " ":
  _, ok := m.selected[m.cursor]
  if ok {
    delete(m.selected, m.cursor)
  } else {
    m.selected[m.cursor] = struct{}{}
  }
}

}

return m, nil
}

TAG:none

发表新评论