-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
326 lines (255 loc) · 7.64 KB
/
table.go
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//
// tui.Table
//
// Display, search, and select tabular data and render into a tui.View
//
// General data flow:
// 1. Update -> add new records
// 2. Fetch -> capture string values from records
// 3. Search -> filter values into results
// 4. Draw -> render results into table
//
// TODO: Extract style into config
// TODO: Extract widths generation to be recalled upon Width change
package tui
import (
"bytes"
"fmt"
"github.com/shreve/tui/ansi"
"reflect"
"strings"
"sync"
"unicode/utf8"
)
// Table is a structure for drawing tabular data. Data is any slice of structs.
// Supply column names and widths to pull data out of records and draw.
type Table struct {
// Values are extracted from records. This is done once to avoid using
// reflection more than necessary.
values []row
// Results are indices of values returned from a search.
results []int
// Are we searching, and what for? Run a strings.Contains query on each
// value for a record to select.
searching bool
query string
// Go structs supplied to the table. Panic if these aren't structs.
records []interface{}
// Generated widths for columns based on content length and Table width
widths []int
// General lock for multi-threaded weirdness
lock sync.Mutex
// Which row of the table is selected?
Cursor Cursor
// What are the names of the columns?
Columns []string
// At what size are we able to render this table?
Height int
Width int
}
// row is a stringified record, which points back to its entry in records
type row struct {
recordIndex int
columns []string
}
// Update the internal data of the table.
func (t *Table) Update(records interface{}, columns []string) {
t.lock.Lock()
defer t.lock.Unlock()
t.Columns = columns
// The supplied records must be a slice of structs
s := reflect.ValueOf(records)
if s.Kind() != reflect.Slice {
panic("Non-slice supplied to tui.Table.Update")
}
t.records = make([]interface{}, s.Len())
if s.Len() > 0 {
if s.Index(0).Kind() != reflect.Struct {
panic("Slice of non-structs was supplied to tui.Table.Update")
}
}
for i := 0; i < s.Len(); i++ {
t.records[i] = s.Index(i).Interface()
}
if len(t.records) == 0 {
return
}
// Pull strings out of our []interface{} records
// Reset the collection
t.values = make([]row, len(t.records))
lengths := make([]int, len(t.Columns))
// For each row:
for i := 0; i < len(t.records); i++ {
// Save the record it came from.
row := row{i, make([]string, len(t.Columns))}
// For each column:
for j := 0; j < len(t.Columns); j++ {
// Get the value from the record by this column's name
value := reflect.ValueOf(t.records[i]).FieldByName(t.Columns[j])
// Cast the value to a string.
row.columns[j] = fmt.Sprintf("%v", value)
lengths[j] += len(row.columns[j])
}
// Add the found row to the list of values
t.values[i] = row
}
total_length := 0
for i := 0; i < len(lengths); i++ {
lengths[i] /= len(t.records)
total_length += lengths[i]
}
t.widths = make([]int, len(t.Columns))
for i := 0; i < len(lengths); i++ {
pct := float32(lengths[i]) / float32(total_length)
t.widths[i] = int(pct * float32(t.Width))
}
for i := 0; sum(t.widths) <= (t.Width + 1); i++ {
t.widths[i%len(t.widths)]++
}
// Bound our cursor to the potentially newly modified list
t.Cursor.SetSize(len(t.values), 1)
// Reset the filter
t.resetResults()
}
func (t *Table) Search(query string) {
t.lock.Lock()
defer t.lock.Unlock()
t.searching = true
t.query = query
t.results = make([]int, 0)
// Get our search query ready (lower to lower comparison)
needle := strings.ToLower(t.query)
for i := 0; i < len(t.values); i++ {
matched := false
for j := 0; j < len(t.Columns); j++ {
haystack := strings.ToLower(t.values[i].columns[j])
// If we are searching, see if this value matches the query.
if strings.Contains(haystack, needle) {
matched = true
}
}
if matched {
t.results = append(t.results, i)
}
}
// Bound our cursor to the potentially newly modified list
t.Cursor.SetSize(len(t.results), 1)
}
// Compute the table into a View
func (t *Table) Draw() (view View) {
t.lock.Lock()
defer t.lock.Unlock()
if len(t.records) == 0 {
return make(View, t.Height)
}
view = append(view, t.Heading())
return append(view, t.Body()...)
}
var titleDisplay = ansi.DisplayCode(ansi.NewDisplay(ansi.Black, ansi.White))
var highlightedDisplay = ansi.DisplayCode(ansi.NewDisplay(ansi.Black, ansi.Yellow))
// Draw the column names
func (t *Table) Heading() string {
out := bytes.NewBufferString(titleDisplay)
for i := 0; i < len(t.Columns); i++ {
out.WriteString(rightPad(t.Columns[i], t.widths[i]))
}
out.WriteString(ansi.DisplayResetCode)
return out.String()
}
// Pull out the data from records based on column names
func (t *Table) Body() View {
out := make(View, t.Height)
if len(t.records) == 0 {
return out
}
// Provided height includes heading. Body height is one less.
height := t.Height - 1
// When searching, we append a line about the search, so the viewport is one
// row shorter.
if t.searching {
height -= 1
}
// If we can't fill the whole space, only fill with what we have.
if len(t.results) < height {
height = len(t.results)
}
// If the current selection is beyond the height of our viewport, we need to
// use an offset to shift our contents so the selection is in view.
selected, _ := t.Cursor.Position()
offset := 0
if selected > (height - 2) {
offset = selected - height + 1
}
// For the height of our viewport:
for i := 0; i < height; i++ {
// Pick a row of data.
index := i + offset
line := bytes.NewBufferString(ansi.DisplayResetCode)
// If it's selected, highlight it.
if index == selected {
line.WriteString(highlightedDisplay)
}
// Write out the content for each column.
for j := 0; j < len(t.Columns); j++ {
value := t.values[t.results[index]].columns[j]
line.WriteString(rightPad(fmt.Sprintf("%s", value), t.widths[j]))
}
// Reset the style and save the line
line.WriteString(ansi.DisplayResetCode)
out[i] = line.String()
}
// If we are currently searching, add info about the search to the bottom
if t.searching {
searchLine := bytes.NewBufferString(ansi.DisplayResetCode)
searchLine.WriteString(titleDisplay)
searchLine.WriteString(
rightPad(fmt.Sprintf(" Searching For \"%s\"", t.query), t.Width))
out[len(out)-1] = searchLine.String()
}
return out
}
// If we're keeping this table around, we need to be able to clear search mode.
func (t *Table) ClearSearch() {
t.searching = false
}
// Returns the index of the record associated with the currently selected value.
func (t *Table) SelectedRecord() int {
selected, _ := t.Cursor.Position()
return t.values[t.results[selected]].recordIndex
}
func (t *Table) resetResults() {
t.results = make([]int, len(t.values))
for i := 0; i < len(t.values); i++ {
t.results[i] = i
}
}
// Make a table-cell-style string out of an input to be a given total length
// We use special utf8 functions rather than just len() here because multi-byte
// characters mess up alignment. We want to do our best to have `length` visible
// runes rather than just bytes.
func rightPad(input string, length int) string {
truncated := true
for utf8.RuneCountInString(input) < (length - 2) {
input += " "
truncated = false
}
out := bytes.NewBufferString(" ")
for utf8.RuneCountInString(out.String()) < length-2 {
r, size := utf8.DecodeRuneInString(input)
out.WriteRune(r)
input = input[size:]
}
out.WriteString(" ")
result := out.String()
if truncated {
index := len(result) - 2
result = result[:index] + "…" + result[index+1:]
}
return result
}
func sum(nums []int) (n int) {
for _, i := range nums {
n += i
}
return
}