gt/internal/interactive/interactive.go

596 lines
13 KiB
Go
Raw Normal View History

// Package interactive implements a charm-powered table to display files.
2024-07-28 21:06:41 -04:00
package interactive
import (
"fmt"
"math"
"path/filepath"
"slices"
"strings"
"git.burning.moe/celediel/gt/internal/dirs"
"git.burning.moe/celediel/gt/internal/files"
2024-07-28 21:06:41 -04:00
"git.burning.moe/celediel/gt/internal/interactive/modes"
"git.burning.moe/celediel/gt/internal/interactive/sorting"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/table"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/dustin/go-humanize"
)
const (
uncheck string = "☐"
check string = "☑"
space string = " "
woffset int = 13 // why this number, I don't know
hoffset int = 6
2024-07-30 16:03:33 -04:00
poffset int = 2
// TODO: figure these out dynamically based on longest of each
filenameColumn float64 = 0.46
pathColumn float64 = 0.25
dateColumn float64 = 0.15
sizeColumn float64 = 0.12
checkColumn float64 = 0.02
// TODO: make these configurable or something
borderbg string = "5"
hoveritembg string = "13"
black string = "0"
darkblack string = "8"
white string = "7"
darkgray string = "15"
)
var (
style = lipgloss.NewStyle().
BorderStyle(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color(borderbg))
regulartext = lipgloss.NewStyle().
2024-07-30 16:03:33 -04:00
Padding(0, poffset)
darktext = lipgloss.NewStyle().
Foreground(lipgloss.Color(darkgray))
darkertext = lipgloss.NewStyle().
Foreground(lipgloss.Color(darkblack))
darkesttext = lipgloss.NewStyle().
Foreground(lipgloss.Color(black))
)
type model struct {
2024-07-15 18:32:33 -04:00
table table.Model
keys keyMap
selected map[string]bool
2024-07-21 23:54:22 -04:00
selectsize int64
2024-07-15 18:32:33 -04:00
readonly bool
once bool
2024-07-15 18:32:33 -04:00
termheight int
termwidth int
2024-07-15 18:32:33 -04:00
mode modes.Mode
sorting sorting.Sorting
workdir string
files files.Files
}
func newModel(fls []files.File, width, height int, readonly, once bool, workdir string, mode modes.Mode) model {
var (
2024-07-30 16:03:33 -04:00
fwidth = int(math.Round(float64(width-woffset) * filenameColumn))
owidth = int(math.Round(float64(width-woffset) * pathColumn))
dwidth = int(math.Round(float64(width-woffset) * dateColumn))
swidth = int(math.Round(float64(width-woffset) * sizeColumn))
cwidth = int(math.Round(float64(width-woffset) * checkColumn))
theight = min(height-hoffset, len(fls))
mdl = model{
2024-07-15 18:32:33 -04:00
keys: defaultKeyMap(),
readonly: readonly,
once: once,
2024-07-15 18:32:33 -04:00
termheight: height,
termwidth: width,
2024-07-15 18:32:33 -04:00
mode: mode,
selected: map[string]bool{},
2024-07-21 23:54:22 -04:00
selectsize: 0,
files: fls,
}
)
2024-07-15 19:31:58 -04:00
if workdir != "" {
mdl.workdir = filepath.Clean(workdir)
2024-07-15 19:31:58 -04:00
}
rows := mdl.freshRows()
var datecolumn string
switch mdl.mode {
case modes.Trashing:
datecolumn = "modified"
default:
datecolumn = "trashed"
}
columns := []table.Column{
{Title: "filename", Width: fwidth},
{Title: "path", Width: owidth},
{Title: datecolumn, Width: dwidth},
{Title: "size", Width: swidth},
}
if !mdl.readonly {
columns = append(columns, table.Column{Title: uncheck, Width: cwidth})
} else {
columns[0].Width += cwidth
}
mdl.table = createTable(columns, rows, theight)
mdl.sorting = sorting.Name
mdl.sort()
return mdl
}
type keyMap struct {
mark key.Binding
doit key.Binding
todo key.Binding
nada key.Binding
invr key.Binding
rstr key.Binding
clen key.Binding
sort key.Binding
rort key.Binding
quit key.Binding
}
func defaultKeyMap() keyMap {
return keyMap{
mark: key.NewBinding(
key.WithKeys(space),
key.WithHelp("space", "toggle"),
),
doit: key.NewBinding(
key.WithKeys("enter", "y"),
key.WithHelp("enter/y", "confirm"),
),
todo: key.NewBinding(
key.WithKeys("a", "ctrl+a"),
2024-07-28 21:07:23 -04:00
key.WithHelp("a", "all"),
),
nada: key.NewBinding(
key.WithKeys("n", "ctrl+n"),
2024-06-20 00:36:13 -04:00
key.WithHelp("n", "none"),
),
invr: key.NewBinding(
key.WithKeys("i", "ctrl+i"),
2024-06-20 00:36:13 -04:00
key.WithHelp("i", "invert"),
),
clen: key.NewBinding(
key.WithKeys("c"),
2024-06-20 00:36:13 -04:00
key.WithHelp("c", "clean"),
),
rstr: key.NewBinding(
key.WithKeys("r"),
2024-06-20 00:36:13 -04:00
key.WithHelp("r", "restore"),
),
sort: key.NewBinding(
key.WithKeys("s"),
2024-07-28 21:07:23 -04:00
key.WithHelp("s/S", "sort"),
),
rort: key.NewBinding(
key.WithKeys("S"),
2024-07-28 21:07:23 -04:00
key.WithHelp("S", "sort (reverse)"),
),
quit: key.NewBinding(
key.WithKeys("q", "ctrl+c"),
key.WithHelp("q", "quit"),
),
}
}
func (m model) Init() tea.Cmd {
/* if m.onePage() {
m.table.SetStyles(makeUnselectedStyle())
m.unselectAll()
return tea.Quit
} */
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
if m.once {
return m.quit(m.readonly)
}
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case key.Matches(msg, m.keys.mark):
2024-06-29 22:54:15 -04:00
m.toggleItem(m.table.Cursor())
case key.Matches(msg, m.keys.doit):
if !m.readonly && m.mode != modes.Interactive {
return m.quit(false)
}
case key.Matches(msg, m.keys.nada):
2024-06-29 22:54:15 -04:00
m.unselectAll()
case key.Matches(msg, m.keys.todo):
2024-06-29 22:54:15 -04:00
m.selectAll()
case key.Matches(msg, m.keys.invr):
2024-06-29 22:54:15 -04:00
m.invertSelection()
case key.Matches(msg, m.keys.clen):
return m.execute(modes.Cleaning)
case key.Matches(msg, m.keys.rstr):
return m.execute(modes.Restoring)
case key.Matches(msg, m.keys.sort):
m.sorting = m.sorting.Next()
m.sort()
case key.Matches(msg, m.keys.rort):
m.sorting = m.sorting.Prev()
m.sort()
case key.Matches(msg, m.keys.quit):
return m.quit(true)
}
}
// pass events along to the table
m.table, cmd = m.table.Update(msg)
return m, cmd
}
func (m model) View() string {
var panels []string
if m.mode != modes.Listing {
panels = append(panels, m.header())
}
panels = append(panels, style.Render(m.table.View()), m.footer())
return lipgloss.JoinVertical(lipgloss.Top, panels...)
}
func (m model) showHelp() string {
// TODO: maybe use bubbletea built in help
var keys = []string{
fmt.Sprintf("%s %s (%s)", darktext.Render(m.keys.sort.Help().Key), darkertext.Render(m.keys.sort.Help().Desc), m.sorting.String()),
fmt.Sprintf("%s %s", darktext.Render(m.keys.quit.Help().Key), darkertext.Render(m.keys.quit.Help().Desc)),
}
if !m.readonly {
if m.mode != modes.Interactive {
keys = append([]string{
fmt.Sprintf("%s %s", darktext.Render(m.keys.doit.Help().Key), darkertext.Render(m.keys.doit.Help().Desc)),
}, keys...)
}
keys = append([]string{
fmt.Sprintf("%s %s", darktext.Render(m.keys.mark.Help().Key), darkertext.Render(m.keys.mark.Help().Desc)),
}, keys...)
}
return strings.Join(keys, darkesttext.Render(" • "))
}
func (m model) header() string {
var (
right, left string
spacerWidth int
keys = []string{
fmt.Sprintf("%s %s", darktext.Render(m.keys.rstr.Help().Key), darkertext.Render(m.keys.rstr.Help().Desc)),
fmt.Sprintf("%s %s", darktext.Render(m.keys.clen.Help().Key), darkertext.Render(m.keys.clen.Help().Desc)),
}
selectKeys = []string{
2024-06-20 00:36:13 -04:00
fmt.Sprintf("%s %s", darktext.Render(m.keys.todo.Help().Key), darkertext.Render(m.keys.todo.Help().Desc)),
fmt.Sprintf("%s %s", darktext.Render(m.keys.nada.Help().Key), darkertext.Render(m.keys.nada.Help().Desc)),
fmt.Sprintf("%s %s", darktext.Render(m.keys.invr.Help().Key), darkertext.Render(m.keys.invr.Help().Desc)),
}
dot = darkesttext.Render("•")
wideDot = darkesttext.Render(" • ")
)
right = " " // to offset from the table border
switch m.mode {
case modes.Interactive:
right += strings.Join(keys, wideDot)
default:
right += m.mode.String()
if m.workdir != "" {
right += fmt.Sprintf(" in %s", dirs.UnExpand(m.workdir, ""))
}
}
right += fmt.Sprintf(" %s %s", dot, strings.Join(selectKeys, wideDot))
left = fmt.Sprintf("%d/%d %s %s", len(m.selected), len(m.table.Rows()), dot, humanize.Bytes(uint64(m.selectsize)))
// offset of 2 again because of table border
2024-07-30 16:03:33 -04:00
spacerWidth = m.termwidth - lipgloss.Width(right) - lipgloss.Width(left) - poffset
if spacerWidth <= 0 {
spacerWidth = 1 // always at least one space
}
return fmt.Sprintf("%s%s%s", right, strings.Repeat(" ", spacerWidth), left)
}
func (m model) footer() string {
return regulartext.Render(m.showHelp())
}
func (m model) quit(unselectAll bool) (model, tea.Cmd) {
if unselectAll {
2024-06-29 22:54:15 -04:00
m.unselectAll()
} else {
m.onlySelected()
}
m.table.SetStyles(makeUnselectedStyle())
return m, tea.Quit
}
func (m model) execute(mode modes.Mode) (model, tea.Cmd) {
if m.mode != modes.Interactive || len(m.selected) <= 0 {
var cmd tea.Cmd
return m, cmd
}
m.mode = mode
m.onlySelected()
m.table.SetStyles(makeUnselectedStyle())
return m, tea.Quit
}
2024-07-15 18:32:33 -04:00
func (m model) selectedFiles() (outfile files.Files) {
for _, file := range m.files {
if m.selected[file.String()] {
outfile = append(outfile, file)
}
2024-07-15 18:32:33 -04:00
}
return
}
/* func (m model) onePage() bool {
x := m.termheight
y := len(m.table.Rows()) + hoffset
if x > y && m.readonly {
return true
}
return false
} */
func (m *model) freshRows() (rows []table.Row) {
for _, file := range m.files {
row := newRow(file, m.workdir)
if !m.readonly {
row = append(row, getCheck(false))
}
rows = append(rows, row)
}
return
}
func (m *model) onlySelected() {
var rows = make([]table.Row, 0)
for _, row := range m.table.Rows() {
if row[4] == check {
rows = append(rows, row)
} else {
rows = append(rows, table.Row{})
}
}
m.table.SetRows(rows)
}
// updateRow updates row of provided index with provided row.
2024-06-29 22:54:15 -04:00
func (m *model) updateRow(index int, selected bool) {
rows := m.table.Rows()
row := rows[index]
rows[index] = table.Row{
row[0],
row[1],
row[2],
row[3],
getCheck(selected),
}
m.table.SetRows(rows)
}
2024-06-29 22:54:15 -04:00
func (m *model) updateRows(selected bool) {
var newrows = []table.Row{}
for _, row := range m.table.Rows() {
newRow := table.Row{
row[0],
row[1],
row[2],
row[3],
getCheck(selected),
}
newrows = append(newrows, newRow)
}
m.table.SetRows(newrows)
}
2024-06-29 22:54:15 -04:00
func (m *model) toggleItem(index int) (selected bool) {
if m.readonly {
return false
}
2024-07-15 18:32:33 -04:00
name := m.files[index].String()
2024-07-21 23:54:22 -04:00
size := m.files[index].Filesize()
2024-07-15 18:32:33 -04:00
// select the thing
2024-07-15 18:32:33 -04:00
if v, ok := m.selected[name]; v && ok {
// already selected
2024-07-15 18:32:33 -04:00
delete(m.selected, name)
selected = false
2024-07-21 23:54:22 -04:00
m.selectsize -= size
} else {
// not selected
2024-07-15 18:32:33 -04:00
m.selected[name] = true
selected = true
2024-07-21 23:54:22 -04:00
m.selectsize += size
}
// update the rows with the state
2024-06-29 22:54:15 -04:00
m.updateRow(index, selected)
return
}
2024-06-29 22:54:15 -04:00
func (m *model) selectAll() {
if m.readonly {
return
}
2024-07-15 18:32:33 -04:00
m.selected = map[string]bool{}
2024-07-21 23:54:22 -04:00
m.selectsize = 0
2024-07-15 20:55:51 -04:00
for i := range m.table.Rows() {
2024-07-15 18:32:33 -04:00
m.selected[m.files[i].String()] = true
2024-07-21 23:54:22 -04:00
m.selectsize += m.files[i].Filesize()
}
2024-06-29 22:54:15 -04:00
m.updateRows(true)
}
2024-06-29 22:54:15 -04:00
func (m *model) unselectAll() {
if m.readonly {
return
}
2024-07-15 18:32:33 -04:00
m.selected = map[string]bool{}
2024-07-21 23:54:22 -04:00
m.selectsize = 0
2024-06-29 22:54:15 -04:00
m.updateRows(false)
}
2024-06-29 22:54:15 -04:00
func (m *model) invertSelection() {
2024-07-15 18:32:33 -04:00
if m.readonly {
return
}
var newrows []table.Row
for index, row := range m.table.Rows() {
2024-07-15 18:32:33 -04:00
name := m.files[index].String()
2024-07-21 23:54:22 -04:00
size := m.files[index].Filesize()
2024-07-15 18:32:33 -04:00
if v, ok := m.selected[name]; v && ok {
delete(m.selected, name)
2024-07-21 23:54:22 -04:00
m.selectsize -= size
newrows = append(newrows, table.Row{
row[0],
row[1],
row[2],
row[3],
getCheck(false),
})
} else {
2024-07-15 18:32:33 -04:00
m.selected[name] = true
2024-07-21 23:54:22 -04:00
m.selectsize += size
newrows = append(newrows, table.Row{
row[0],
row[1],
row[2],
row[3],
getCheck(true),
})
}
}
m.table.SetRows(newrows)
}
func (m *model) sort() {
slices.SortStableFunc(m.files, m.sorting.Sorter())
var rows = []table.Row{}
2024-07-15 18:32:33 -04:00
for _, file := range m.files {
r := newRow(file, m.workdir)
2024-07-15 18:32:33 -04:00
if !m.readonly {
r = append(r, getCheck(m.selected[file.String()]))
}
rows = append(rows, r)
}
2024-07-15 18:32:33 -04:00
m.table.SetRows(rows)
}
func Select(fls files.Files, width, height int, readonly, once bool, workdir string, mode modes.Mode) (files.Files, modes.Mode, error) {
mdl := newModel(fls, width, height, readonly, once, workdir, mode)
2024-07-15 18:32:33 -04:00
endmodel, err := tea.NewProgram(mdl).Run()
if err != nil {
return fls, 0, err
2024-07-15 18:32:33 -04:00
}
m, ok := endmodel.(model)
if !ok {
return fls, 0, fmt.Errorf("model isn't the right type?? what has happened")
}
2024-07-15 18:32:33 -04:00
return m.selectedFiles(), m.mode, nil
}
2024-07-28 21:07:07 -04:00
func newRow(file files.File, workdir string) table.Row {
var time, bar string
time = humanize.Time(file.Date())
2024-07-28 21:07:07 -04:00
if file.IsDir() {
2024-07-30 16:03:33 -04:00
bar = strings.Repeat("─", poffset+1)
2024-07-28 21:07:07 -04:00
} else {
bar = humanize.Bytes(uint64(file.Filesize()))
2024-07-28 21:07:07 -04:00
}
return table.Row{
dirs.UnEscape(file.Name()),
dirs.UnExpand(filepath.Dir(file.Path()), workdir),
time,
bar,
2024-07-28 21:07:07 -04:00
}
}
func getCheck(selected bool) (ourcheck string) {
if selected {
ourcheck = check
} else {
ourcheck = uncheck
}
return
}
2024-07-15 18:32:33 -04:00
func createTable(columns []table.Column, rows []table.Row, height int) table.Model {
tbl := table.New(
table.WithColumns(columns),
table.WithRows(rows),
table.WithFocused(true),
table.WithHeight(height),
)
tbl.KeyMap = fixTableKeymap()
tbl.SetStyles(makeStyle())
return tbl
}
func fixTableKeymap() table.KeyMap {
keys := table.DefaultKeyMap()
// remove spacebar from default page down keybind, but keep the rest
keys.PageDown.SetKeys(
slices.DeleteFunc(keys.PageDown.Keys(), func(s string) bool {
return s == space
})...,
)
return keys
}
func makeStyle() table.Styles {
style := table.DefaultStyles()
style.Header = style.Header.
BorderStyle(lipgloss.NormalBorder()).
BorderForeground(lipgloss.Color(black)).
BorderBottom(true).
Bold(false)
style.Selected = style.Selected.
Foreground(lipgloss.Color(white)).
Background(lipgloss.Color(hoveritembg)).
Bold(false)
return style
}
func makeUnselectedStyle() table.Styles {
style := makeStyle()
style.Selected = style.Selected.
Foreground(lipgloss.NoColor{}).
Background(lipgloss.NoColor{}).
Bold(false)
return style
}