From 865c6dc23099e129cb3ba9709b2926734144e605 Mon Sep 17 00:00:00 2001 From: tjp Date: Tue, 23 Jan 2024 22:42:18 -0700 Subject: Printer abstraction --- tui.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 10 deletions(-) (limited to 'tui.go') diff --git a/tui.go b/tui.go index 12bb665..c131110 100644 --- a/tui.go +++ b/tui.go @@ -4,40 +4,77 @@ import ( "os" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/bubbles/viewport" ) type TUIModel struct { State *BrowserState + Viewport viewport.Model + inited bool } -func NewTUIModel(state *BrowserState) TUIModel { - return TUIModel{State: state} +func NewTUIModel(state *BrowserState) *TUIModel { + return &TUIModel{State: state} } -func (model TUIModel) Init() tea.Cmd { +func (model *TUIModel) Init() tea.Cmd { return nil } -func (model TUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { +func (model *TUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyMsg: switch msg.String() { - case "ctrl+c", "ctrl+d", "q": + case "ctrl+c", "q": return model, tea.Quit + case "g": + model.Viewport.GotoTop() + return model, nil + case "G": + model.Viewport.GotoBottom() + return model, nil } + case tea.WindowSizeMsg: + model.inited = true + model.Viewport.Width = msg.Width + model.Viewport.Height = msg.Height - 1 } - return model, nil + var cmd tea.Cmd + model.Viewport, cmd = model.Viewport.Update(msg) + + return model, cmd } -func (model TUIModel) View() string { - return "pardon our dust" +func (model *TUIModel) View() string { + return model.Viewport.View() } -func runTUI(state *BrowserState) { - p := tea.NewProgram(NewTUIModel(state)) +func runTUI(state *BrowserState, args []string) { + model := NewTUIModel(state) + state.Printer = (*TUIPrinter)(model) + + if len(args) > 0 { + if err := Go(state, args[0]); err != nil { + writeError(err.Error()) + } + } + + p := tea.NewProgram(model, tea.WithAltScreen()) if _, err := p.Run(); err != nil { writeError(err.Error()) os.Exit(1) } } + +type TUIPrinter TUIModel + +func (p *TUIPrinter) PrintModal(state *BrowserState, contents []byte) error { + (*TUIModel)(p).Viewport.SetContent(string(contents)) + return nil +} + +func (p *TUIPrinter) PrintPage(state *BrowserState, body string) error { + (*TUIModel)(p).Viewport.SetContent(body) + return nil +} -- cgit v1.2.3