summaryrefslogtreecommitdiffhomepage
path: root/internal/tui/components/logs/table.go
blob: e8500920519a630587a3164d3dd908c228d76e26 (plain)
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package logs

import (
	"context"
	"log/slog"

	"github.com/charmbracelet/bubbles/key"
	"github.com/charmbracelet/bubbles/table"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/sst/opencode/internal/app"
	"github.com/sst/opencode/internal/logging"
	"github.com/sst/opencode/internal/pubsub"
	"github.com/sst/opencode/internal/tui/layout"
	"github.com/sst/opencode/internal/tui/state"
	"github.com/sst/opencode/internal/tui/theme"
)

type TableComponent interface {
	tea.Model
	layout.Sizeable
	layout.Bindings
}

type tableCmp struct {
	app           *app.App
	table         table.Model
	focused       bool
	logs          []logging.Log
	selectedLogID string
}

type selectedLogMsg logging.Log

type LogsLoadedMsg struct {
	logs []logging.Log
}

func (i *tableCmp) Init() tea.Cmd {
	return i.fetchLogs()
}

func (i *tableCmp) fetchLogs() tea.Cmd {
	return func() tea.Msg {
		ctx := context.Background()

		var logs []logging.Log
		var err error

		// Limit the number of logs to improve performance
		const logLimit = 100
		if i.app.CurrentSession.ID == "" {
			logs, err = i.app.Logs.ListAll(ctx, logLimit)
		} else {
			logs, err = i.app.Logs.ListBySession(ctx, i.app.CurrentSession.ID)
		}

		if err != nil {
			slog.Error("Failed to fetch logs", "error", err)
			return nil
		}

		return LogsLoadedMsg{logs: logs}
	}
}

func (i *tableCmp) updateRows() tea.Cmd {
	return func() tea.Msg {
		rows := make([]table.Row, 0, len(i.logs))

		for _, log := range i.logs {
			timeStr := log.Timestamp.Local().Format("15:04:05")

			// Include ID as hidden first column for selection
			row := table.Row{
				log.ID,
				timeStr,
				log.Level,
				log.Message,
			}
			rows = append(rows, row)
		}

		i.table.SetRows(rows)
		return nil
	}
}

func (i *tableCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmds []tea.Cmd

	switch msg := msg.(type) {
	case LogsLoadedMsg:
		i.logs = msg.logs
		return i, i.updateRows()

	case state.SessionSelectedMsg:
		return i, i.fetchLogs()

	case pubsub.Event[logging.Log]:
		if msg.Type == logging.EventLogCreated {
			// Add the new log to our list
			i.logs = append([]logging.Log{msg.Payload}, i.logs...)
			// Keep the list at a reasonable size
			if len(i.logs) > 100 {
				i.logs = i.logs[:100]
			}
			return i, i.updateRows()
		}
		return i, nil
	}

	// Only process keyboard input when focused
	if _, ok := msg.(tea.KeyMsg); ok && !i.focused {
		return i, nil
	}

	t, cmd := i.table.Update(msg)
	cmds = append(cmds, cmd)
	i.table = t

	selectedRow := i.table.SelectedRow()
	if selectedRow != nil {
		// Only send message if it's a new selection
		if i.selectedLogID != selectedRow[0] {
			cmds = append(cmds, func() tea.Msg {
				for _, log := range i.logs {
					if log.ID == selectedRow[0] {
						return selectedLogMsg(log)
					}
				}
				return nil
			})
		}

		i.selectedLogID = selectedRow[0]
	}

	return i, tea.Batch(cmds...)
}

func (i *tableCmp) View() string {
	t := theme.CurrentTheme()
	defaultStyles := table.DefaultStyles()
	defaultStyles.Selected = defaultStyles.Selected.Foreground(t.Primary())
	i.table.SetStyles(defaultStyles)
	return i.table.View()
}

func (i *tableCmp) GetSize() (int, int) {
	return i.table.Width(), i.table.Height()
}

func (i *tableCmp) SetSize(width int, height int) tea.Cmd {
	i.table.SetWidth(width)
	i.table.SetHeight(height)
	columns := i.table.Columns()

	// Calculate widths for visible columns
	timeWidth := 8  // Fixed width for Time column
	levelWidth := 7 // Fixed width for Level column

	// Message column gets the remaining space
	messageWidth := width - timeWidth - levelWidth - 5 // 5 for padding and borders

	// Set column widths
	columns[0].Width = 0 // ID column (hidden)
	columns[1].Width = timeWidth
	columns[2].Width = levelWidth
	columns[3].Width = messageWidth

	i.table.SetColumns(columns)
	return nil
}

func (i *tableCmp) BindingKeys() []key.Binding {
	return layout.KeyMapToSlice(i.table.KeyMap)
}

func NewLogsTable(app *app.App) TableComponent {
	columns := []table.Column{
		{Title: "ID", Width: 0}, // ID column with zero width
		{Title: "Time", Width: 8},
		{Title: "Level", Width: 7},
		{Title: "Message", Width: 30},
	}

	tableModel := table.New(
		table.WithColumns(columns),
	)
	tableModel.Focus()
	return &tableCmp{
		app:   app,
		table: tableModel,
		logs:  []logging.Log{},
	}
}

// Focus implements the focusable interface
func (i *tableCmp) Focus() {
	i.focused = true
	i.table.Focus()
}

// Blur implements the blurable interface
func (i *tableCmp) Blur() {
	i.focused = false
	i.table.Blur()
}