Description
package main
import (
"fmt"
"os"
"runtime"
tea "github.com/charmbracelet/bubbletea"
)
// 模型结构体
type model struct {
choices []string // 菜单选项
cursor int // 当前选中的选项
selected map[int]struct{} // 已选择的选项
osInfo string // 系统信息
}
// 初始化函数
func initialModel() model {
return model{
choices: []string{"选项1", "选项2", "选项3", "退出"},
selected: make(map[int]struct{}),
osInfo: fmt.Sprintf("%s %s (Arch: %s)", runtime.GOOS, runtime.Version(), runtime.GOARCH),
}
}
// 初始化命令
func (m model) Init() tea.Cmd {
return nil
}
// 更新逻辑
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.choices)-1 {
m.cursor++
}
case "enter", " ":
if m.cursor == len(m.choices)-1 { // 退出选项
return m, tea.Quit
}
// 切换选择状态
if _, ok := m.selected[m.cursor]; ok {
delete(m.selected, m.cursor)
} else {
m.selected[m.cursor] = struct{}{}
}
}
}
return m, nil
}
// 界面渲染
func (m model) View() string {
s := "Bubble Tea 兼容性测试程序\n\n"
s += fmt.Sprintf("系统信息: %s\n\n", m.osInfo)
s += "使用方向键(↑↓)移动,空格选择,回车确认,q退出\n\n"
for i, choice := range m.choices {
cursor := " " // 没有光标
if m.cursor == i {
cursor = ">" // 显示光标
}
checked := " " // 未选中
if _, ok := m.selected[i]; ok {
checked = "x" // 已选中
}
s += fmt.Sprintf("%s [%s] %s\n", cursor, checked, choice)
}
s += "\n按Q退出程序\n"
return s
}
func main() {
// 创建日志文件记录错误
f, err := os.OpenFile("tea_error.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
fmt.Println("无法创建日志文件:", err)
os.Exit(1)
}
defer f.Close()
// 同时输出到文件和终端
p := tea.NewProgram(initialModel(), tea.WithOutput(f))
// 运行程序
if _, err := p.Run(); err != nil {
fmt.Println("程序错误:", err)
os.Exit(1)
}
}