Skip to content

Commit

Permalink
Print selected tea-list item as JSON upon exit
Browse files Browse the repository at this point in the history
  • Loading branch information
lukasschwab committed Nov 25, 2024
1 parent 83dfb46 commit a2ae183
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions cmd/tir/cmd/list.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"encoding/json"
"fmt"
"log"
"strings"
Expand Down Expand Up @@ -32,8 +33,10 @@ tir --help.`,
log.Fatalf("Error listing texts: %v", err)
}

if err := renderFunc(texts, cmd); err != nil {
if selectedText, err := renderFunc(texts, cmd); err != nil {
log.Fatalf("error rendering texts: %v", err)
} else if bytes, err := json.MarshalIndent(selectedText, "", "\t"); selectedText != nil && err == nil {
fmt.Println(string(bytes))
}
},
}
Expand Down Expand Up @@ -63,12 +66,12 @@ var rendererOptions = []string{
string(OutputHTML),
}

type renderFunc func(texts []*text.Text, cmd *cobra.Command) error
type renderFunc func(texts []*text.Text, cmd *cobra.Command) (selected *text.Text, err error)

// cli adapter for render.Functions.
func cli(f render.Function) renderFunc {
return func(texts []*text.Text, cmd *cobra.Command) error {
return f(texts, cmd.OutOrStdout())
return func(texts []*text.Text, cmd *cobra.Command) (*text.Text, error) {
return nil, f(texts, cmd.OutOrStdout())
}
}

Expand All @@ -84,12 +87,12 @@ var outputRenderers = map[outputFormat]renderFunc{
// renderTea renders a tea interface for listing/filtering texts. This is a
// little awkward: the List interface lets us pick two strings to display, but
// we really have 4-5.
func renderTea(texts []*text.Text, cmd *cobra.Command) error {
func renderTea(texts []*text.Text, cmd *cobra.Command) (*text.Text, error) {
m := model{list: list.New(items(texts), list.NewDefaultDelegate(), 0, 0)}
m.list.Title = "Articles"
p := tea.NewProgram(m, tea.WithAltScreen())
_, err := p.Run()
return err
finalModel, err := p.Run()
return finalModel.(model).selected.Text, err
}

var docStyle = lipgloss.NewStyle().Margin(1, 2)
Expand All @@ -111,7 +114,8 @@ func (i item) Description() string { return i.Text.Note }
func (i item) FilterValue() string { return i.Title() }

type model struct {
list list.Model
list list.Model
selected item
}

func (m model) Init() tea.Cmd {
Expand All @@ -123,6 +127,9 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case tea.KeyMsg:
if msg.String() == "ctrl+c" {
return m, tea.Quit
} else if msg.String() == "enter" {
m.selected = m.list.SelectedItem().(item)
return m, tea.Quit
}
case tea.WindowSizeMsg:
h, v := docStyle.GetFrameSize()
Expand Down

0 comments on commit a2ae183

Please sign in to comment.