bubbletea/examples/altscreen-toggle/main.go
Carlos Alexandro Becker ea13ffb9a1
feat: allow to suspend bubbletea programs (#1054)
* feat: allow to suspend bubbletea programs

closes #497
closes #1053

* fix: typo

* fix: move things around, add example

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>

* fix: block until CONT

* fix: ResumeMsg

* docs: improve example

* docs: one more example

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>

* fix: examples tests

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>

---------

Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
2024-07-11 18:05:16 -03:00

83 lines
1.5 KiB
Go

package main
import (
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
var (
keywordStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("204")).Background(lipgloss.Color("235"))
helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
)
type model struct {
altscreen bool
quitting bool
suspending bool
}
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.ResumeMsg:
m.suspending = false
return m, nil
case tea.KeyMsg:
switch msg.String() {
case "q", "ctrl+c", "esc":
m.quitting = true
return m, tea.Quit
case "ctrl+z":
m.suspending = true
return m, tea.Suspend
case " ":
var cmd tea.Cmd
if m.altscreen {
cmd = tea.ExitAltScreen
} else {
cmd = tea.EnterAltScreen
}
m.altscreen = !m.altscreen
return m, cmd
}
}
return m, nil
}
func (m model) View() string {
if m.suspending {
return ""
}
if m.quitting {
return "Bye!\n"
}
const (
altscreenMode = " altscreen mode "
inlineMode = " inline mode "
)
var mode string
if m.altscreen {
mode = altscreenMode
} else {
mode = inlineMode
}
return fmt.Sprintf("\n\n You're in %s\n\n\n", keywordStyle.Render(mode)) +
helpStyle.Render(" space: switch modes • ctrl-z: suspend • q: exit\n")
}
func main() {
if _, err := tea.NewProgram(model{}).Run(); err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
}