DEVELOPMENT ENVIRONMENT

~liljamo/tamma

ref: dc8354a6e73a8957dd9d0d9f2662667fcc2a66b1 tamma/types/action.go -rw-r--r-- 1.8 KiB
dc8354a6Jonni Liljamo feat: initial version 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-only, see NOTICE and LICENSE for
 * more information.
 */

package types

import (
	"bytes"
	"fmt"
	"io"
	"strings"
	"text/template"

	"git.src.quest/~skye/tamma/styles"
	"github.com/charmbracelet/bubbles/list"
	tea "github.com/charmbracelet/bubbletea"
)

// ActionItem represents an action to perform.
type ActionItem struct {
	Name         string
	ExecTemplate string
	A            map[string]interface{}
}

// ExecString returns ExecTemplate with template variables filled in.
func (i ActionItem) ExecString(host HostItem) (string, error) {
	i.A["host"] = host
	tmpl, err := template.New(i.Name).Parse(i.ExecTemplate)
	if err != nil {
		return "", err
	}
	var execStringBuffer bytes.Buffer
	err = tmpl.Execute(&execStringBuffer, i)
	if err != nil {
		return "", err
	}
	return execStringBuffer.String(), nil
}

// FilterValue returns the value to filter on.
func (i ActionItem) FilterValue() string { return i.Name }

// ActionItemDelegate represents the visual of an ActionItem.
type ActionItemDelegate struct{}

// Height returns the needed height.
func (d ActionItemDelegate) Height() int { return 1 }

// Spacing returns the needed spacing.
func (d ActionItemDelegate) Spacing() int { return 0 }

// Update is the tea update loop.
func (d ActionItemDelegate) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }

// Render renders the component.
func (d ActionItemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
	i, ok := listItem.(ActionItem)
	if !ok {
		return
	}

	str := fmt.Sprintf("%s", i.Name)

	fn := styles.ListItem.Render
	if index == m.Index() {
		fn = func(s ...string) string {
			return styles.ListItemSelected.Render("> " + strings.Join(s, " "))
		}
	}

	fmt.Fprint(w, fn(str))
}