-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui.go
More file actions
519 lines (451 loc) · 12 KB
/
ui.go
File metadata and controls
519 lines (451 loc) · 12 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package ui
import (
"atlas.sql/internal/db"
"encoding/csv"
"fmt"
"strings"
"time"
"github.com/atotto/clipboard"
"github.com/charmbracelet/bubbles/table"
"github.com/charmbracelet/bubbles/textinput"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
var (
baseStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240"))
focusedStyle = lipgloss.NewStyle().
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("205"))
helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
)
type focus int
const (
focusInput focus = iota
focusTable
)
type ClearStatusMsg struct{}
type Model struct {
db db.Database
input textinput.Model
table table.Model
focus focus
err error
width int
height int
result *db.Result
colOffset int
showDetail bool
showHelp bool
viewport viewport.Model
baseColWidth int
statusMsg string
}
func NewModel(database db.Database) Model {
ti := textinput.New()
ti.Placeholder = "SELECT * FROM users;"
ti.Focus()
ti.CharLimit = 1000
ti.Width = 60
t := table.New(
table.WithFocused(true),
)
s := table.DefaultStyles()
s.Header = s.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color("240")).
BorderBottom(true).
Bold(false)
s.Selected = s.Selected.
Foreground(lipgloss.Color("229")).
Background(lipgloss.Color("57")).
Bold(false)
t.SetStyles(s)
return Model{
db: database,
input: ti,
table: t,
focus: focusInput,
baseColWidth: 20,
}
}
func (m Model) Init() tea.Cmd {
return textinput.Blink
}
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case ClearStatusMsg:
m.statusMsg = ""
return m, nil
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
if m.focus == focusTable {
m.focus = focusInput
m.input.Focus()
return m, nil
}
return m, tea.Quit
case "tab":
if m.focus == focusInput {
m.focus = focusTable
m.input.Blur()
} else {
m.focus = focusInput
m.input.Focus()
}
case "left":
if m.showDetail || m.showHelp {
return m, nil
}
if m.focus == focusTable && m.colOffset > 0 {
m.colOffset--
m.updateTable(m.result)
}
case "right":
if m.showDetail || m.showHelp {
return m, nil
}
if m.focus == focusTable && m.result != nil && m.colOffset < len(m.result.Columns)-1 {
m.colOffset++
m.updateTable(m.result)
}
case "h":
if m.focus == focusInput && !m.showHelp {
m.input, cmd = m.input.Update(msg)
return m, cmd
}
m.showHelp = !m.showHelp
if m.showHelp {
m.showDetail = false
}
return m, nil
case "c":
if m.focus == focusTable && m.result != nil {
return m, m.copyAsCSV()
}
case "v":
if m.focus == focusTable && m.result != nil && len(m.result.Rows) > 0 {
m.showDetail = !m.showDetail
if m.showDetail {
m.updateViewport()
}
}
case "+", "=":
if m.focus == focusTable && m.baseColWidth < 100 {
m.baseColWidth += 5
m.updateTable(m.result)
}
case "-", "_":
if m.focus == focusTable && m.baseColWidth > 10 {
m.baseColWidth -= 5
m.updateTable(m.result)
}
case "ctrl+t":
m.showDetail = false
res, err := m.db.ListTables()
if err != nil {
m.err = err
} else {
m.err = nil
m.colOffset = 0
m.result = res
m.updateTable(res)
m.focus = focusTable
m.input.Blur()
m.table.Focus()
}
case "ctrl+s":
res, err := m.db.ListSchemas()
if err != nil {
m.err = err
} else {
m.err = nil
m.colOffset = 0
m.result = res
m.updateTable(res)
m.focus = focusTable
m.input.Blur()
m.table.Focus()
}
case "enter":
if m.focus == focusInput {
query := m.input.Value()
if query != "" {
res, err := m.db.Query(query)
if err != nil {
m.err = err
} else {
m.err = nil
m.colOffset = 0
m.result = res
m.updateTable(res)
m.focus = focusTable
m.input.Blur()
m.table.Focus()
}
}
}
case "esc":
if m.showHelp {
m.showHelp = false
return m, nil
}
if m.showDetail {
m.showDetail = false
return m, nil
}
if m.focus == focusTable {
m.focus = focusInput
m.input.Focus()
} else {
m.input.SetValue("")
}
}
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
m.input.Width = m.width - 4
m.table.SetWidth(m.width - 4)
// Leave space for Title (3), Input (5), Help (3), Error/Status (2) + Padding
tableHeight := m.height - 15
if tableHeight < 5 {
tableHeight = 5
}
m.table.SetHeight(tableHeight)
m.viewport.Width = m.width - 4
m.viewport.Height = tableHeight
}
if m.showDetail {
m.viewport, cmd = m.viewport.Update(msg)
return m, cmd
}
if m.focus == focusInput {
m.input, cmd = m.input.Update(msg)
} else {
m.table, cmd = m.table.Update(msg)
}
return m, cmd
}
func (m *Model) updateViewport() {
if m.result == nil {
return
}
cursor := m.table.Cursor()
if cursor < 0 || cursor >= len(m.result.Rows) {
return
}
row := m.result.Rows[cursor]
var content string
headerStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("205")).Bold(true)
valueStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("229"))
for i, col := range m.result.Columns {
val := "NULL"
if i < len(row) {
val = row[i]
}
content += headerStyle.Render(col + ":") + "\n"
content += valueStyle.Render(val) + "\n\n"
}
m.viewport.SetContent(content)
}
func (m *Model) updateTable(res *db.Result) {
if res == nil {
return
}
// Use user-defined base column width
minColWidth := m.baseColWidth
if minColWidth < 5 {
minColWidth = 5
}
maxColWidth := minColWidth * 3
// Determine how many columns can fit
availableWidth := m.width - 10
if availableWidth < 20 {
availableWidth = 20
}
// We'll show columns starting from m.colOffset
displayCols := []table.Column{}
currentWidth := 0
var visibleColIndices []int
for i := m.colOffset; i < len(res.Columns); i++ {
// Base width calculation
w := len(res.Columns[i]) + 4
if w < minColWidth {
w = minColWidth
}
if w > maxColWidth {
w = maxColWidth
}
if currentWidth+w > availableWidth && len(displayCols) > 0 {
break
}
displayCols = append(displayCols, table.Column{Title: res.Columns[i], Width: w})
visibleColIndices = append(visibleColIndices, i)
currentWidth += w
}
// If we couldn't even fit one column, force it
if len(displayCols) == 0 && len(res.Columns) > 0 {
idx := m.colOffset
if idx >= len(res.Columns) {
idx = len(res.Columns) - 1
}
displayCols = append(displayCols, table.Column{Title: res.Columns[idx], Width: availableWidth})
visibleColIndices = append(visibleColIndices, idx)
}
rows := []table.Row{}
for _, resRow := range res.Rows {
row := table.Row{}
for _, idx := range visibleColIndices {
if idx < len(resRow) {
row = append(row, resRow[idx])
} else {
row = append(row, "")
}
}
rows = append(rows, row)
}
m.table.SetRows([]table.Row{})
m.table.SetColumns(displayCols)
m.table.SetRows(rows)
}
func (m *Model) copyAsCSV() tea.Cmd {
if m.result == nil {
return nil
}
var b strings.Builder
w := csv.NewWriter(&b)
// Write header
if err := w.Write(m.result.Columns); err != nil {
m.err = err
return nil
}
// Write rows
if err := w.WriteAll(m.result.Rows); err != nil {
m.err = err
return nil
}
w.Flush()
if err := clipboard.WriteAll(b.String()); err != nil {
m.err = err
return nil
}
m.statusMsg = "Copied entire result set to clipboard!"
return tea.Tick(time.Second*3, func(t time.Time) tea.Msg {
return ClearStatusMsg{}
})
}
func (m Model) View() string {
var s string
// Title
s += lipgloss.NewStyle().
Foreground(lipgloss.Color("205")).
Bold(true).
Render(" Atlas SQL ")
s += "\n\n"
if m.showHelp {
s += focusedStyle.Render(m.helpView())
s += "\n\n"
s += helpStyle.Render(" Press 'h' or 'Esc' to return")
return lipgloss.NewStyle().Padding(1, 2).Render(s)
}
// Input Section
inputStyle := baseStyle
if m.focus == focusInput {
inputStyle = focusedStyle
}
s += inputStyle.Render(m.input.View())
s += "\n\n"
// Result Section
if m.err != nil {
s += lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render(fmt.Sprintf("Error: %v", m.err))
s += "\n"
} else if m.result != nil {
if m.showDetail {
s += focusedStyle.Render(m.viewport.View())
s += "\n"
s += helpStyle.Render(fmt.Sprintf(" Detail View: %d columns", len(m.result.Columns)))
s += "\n"
} else {
tableStyle := baseStyle
if m.focus == focusTable {
tableStyle = focusedStyle
}
s += tableStyle.Render(m.table.View())
s += "\n"
colRange := fmt.Sprintf("Cols: %d-%d of %d", m.colOffset+1, m.colOffset+len(m.table.Columns()), len(m.result.Columns))
s += helpStyle.Render(fmt.Sprintf(" %d rows returned • %s", len(m.result.Rows), colRange))
s += "\n"
if m.result.Warning != "" {
s += lipgloss.NewStyle().Foreground(lipgloss.Color("214")).Render(" " + m.result.Warning)
s += "\n"
}
}
}
if m.statusMsg != "" {
s += "\n"
s += lipgloss.NewStyle().
Foreground(lipgloss.Color("229")).
Background(lipgloss.Color("57")).
Padding(0, 1).
Render(m.statusMsg)
s += "\n"
}
// Help Section
s += "\n"
s += helpStyle.Render(" Tab: Switch focus • Enter: Run Query • h: Help • c: Copy CSV")
s += "\n"
s += helpStyle.Render(" ←/→: Scroll Columns • +/-: Width • ↑/↓: Scroll Rows • v: Detail • q: Quit")
return lipgloss.NewStyle().Padding(1, 2).Render(s)
}
func (m Model) helpView() string {
header := lipgloss.NewStyle().Foreground(lipgloss.Color("205")).Bold(true)
key := lipgloss.NewStyle().Foreground(lipgloss.Color("229")).Width(15)
desc := lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
tutorial := lipgloss.NewStyle().Foreground(lipgloss.Color("86"))
lines := []string{
header.Render("Navigation"),
key.Render("Tab") + desc.Render("Switch focus between Input and Table"),
key.Render("↑/↓") + desc.Render("Scroll through result rows"),
key.Render("←/→") + desc.Render("Scroll columns left/right"),
key.Render("+ / -") + desc.Render("Increase / Decrease column width"),
"",
header.Render("Querying"),
key.Render("Enter") + desc.Render("Execute SQL query in input"),
key.Render("Ctrl+T") + desc.Render("List all tables"),
key.Render("Ctrl+S") + desc.Render("List all schemas (databases)"),
"",
header.Render("Data Operations"),
key.Render("v") + desc.Render("Toggle Detail View for selected row"),
key.Render("c") + desc.Render("Copy entire result set as CSV to clipboard"),
"",
header.Render("SQL Quick Tutorial"),
tutorial.Render(" -- Select all columns from a table"),
tutorial.Render(" SELECT * FROM table_name;"),
tutorial.Render(" -- Filter results"),
tutorial.Render(" SELECT * FROM users WHERE age > 18;"),
tutorial.Render(" -- Join tables"),
tutorial.Render(" SELECT u.name, p.title FROM users u JOIN posts p ON u.id = p.user_id;"),
"",
tutorial.Render(" -- Create / Insert / Update / Delete"),
tutorial.Render(" CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT);"),
tutorial.Render(" INSERT INTO items (name) VALUES ('Laptop'), ('Mouse');"),
tutorial.Render(" UPDATE items SET name = 'Mechanical Mouse' WHERE id = 2;"),
tutorial.Render(" DELETE FROM items WHERE id = 1;"),
"",
tutorial.Render(" -- SQLite Meta: List Tables / Schema"),
tutorial.Render(" SELECT name FROM sqlite_master WHERE type='table';"),
tutorial.Render(" PRAGMA table_info(table_name); -- Describe table"),
tutorial.Render(" -- Postgres Meta: List Tables"),
tutorial.Render(" SELECT table_name FROM information_schema.tables;"),
"",
header.Render("General"),
key.Render("h") + desc.Render("Toggle this help screen"),
key.Render("Esc") + desc.Render("Clear input or return from detail/help"),
key.Render("q or Ctrl+C") + desc.Render("Quit application"),
}
return strings.Join(lines, "\n")
}