files.go

  1package repo
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"log"
  7	"path/filepath"
  8
  9	"github.com/alecthomas/chroma/lexers"
 10	"github.com/charmbracelet/bubbles/key"
 11	tea "github.com/charmbracelet/bubbletea"
 12	"github.com/charmbracelet/soft-serve/git"
 13	"github.com/charmbracelet/soft-serve/server/backend"
 14	"github.com/charmbracelet/soft-serve/ui/common"
 15	"github.com/charmbracelet/soft-serve/ui/components/code"
 16	"github.com/charmbracelet/soft-serve/ui/components/selector"
 17)
 18
 19type filesView int
 20
 21const (
 22	filesViewFiles filesView = iota
 23	filesViewContent
 24)
 25
 26var (
 27	errNoFileSelected = errors.New("no file selected")
 28	errBinaryFile     = errors.New("binary file")
 29	errFileTooLarge   = errors.New("file is too large")
 30	errInvalidFile    = errors.New("invalid file")
 31)
 32
 33var (
 34	lineNo = key.NewBinding(
 35		key.WithKeys("l"),
 36		key.WithHelp("l", "toggle line numbers"),
 37	)
 38)
 39
 40// FileItemsMsg is a message that contains a list of files.
 41type FileItemsMsg []selector.IdentifiableItem
 42
 43// FileContentMsg is a message that contains the content of a file.
 44type FileContentMsg struct {
 45	content string
 46	ext     string
 47}
 48
 49// Files is the model for the files view.
 50type Files struct {
 51	common         common.Common
 52	selector       *selector.Selector
 53	ref            *git.Reference
 54	activeView     filesView
 55	repo           backend.Repository
 56	code           *code.Code
 57	path           string
 58	currentItem    *FileItem
 59	currentContent FileContentMsg
 60	lastSelected   []int
 61	lineNumber     bool
 62}
 63
 64// NewFiles creates a new files model.
 65func NewFiles(common common.Common) *Files {
 66	f := &Files{
 67		common:       common,
 68		code:         code.New(common, "", ""),
 69		activeView:   filesViewFiles,
 70		lastSelected: make([]int, 0),
 71		lineNumber:   true,
 72	}
 73	selector := selector.New(common, []selector.IdentifiableItem{}, FileItemDelegate{&common})
 74	selector.SetShowFilter(false)
 75	selector.SetShowHelp(false)
 76	selector.SetShowPagination(false)
 77	selector.SetShowStatusBar(false)
 78	selector.SetShowTitle(false)
 79	selector.SetFilteringEnabled(false)
 80	selector.DisableQuitKeybindings()
 81	selector.KeyMap.NextPage = common.KeyMap.NextPage
 82	selector.KeyMap.PrevPage = common.KeyMap.PrevPage
 83	f.selector = selector
 84	f.code.SetShowLineNumber(f.lineNumber)
 85	return f
 86}
 87
 88// SetSize implements common.Component.
 89func (f *Files) SetSize(width, height int) {
 90	f.common.SetSize(width, height)
 91	f.selector.SetSize(width, height)
 92	f.code.SetSize(width, height)
 93}
 94
 95// ShortHelp implements help.KeyMap.
 96func (f *Files) ShortHelp() []key.Binding {
 97	k := f.selector.KeyMap
 98	switch f.activeView {
 99	case filesViewFiles:
100		copyKey := f.common.KeyMap.Copy
101		copyKey.SetHelp("c", "copy name")
102		return []key.Binding{
103			f.common.KeyMap.SelectItem,
104			f.common.KeyMap.BackItem,
105			k.CursorUp,
106			k.CursorDown,
107			copyKey,
108		}
109	case filesViewContent:
110		copyKey := f.common.KeyMap.Copy
111		copyKey.SetHelp("c", "copy content")
112		b := []key.Binding{
113			f.common.KeyMap.UpDown,
114			f.common.KeyMap.BackItem,
115			copyKey,
116		}
117		lexer := lexers.Match(f.currentContent.ext)
118		lang := ""
119		if lexer != nil && lexer.Config() != nil {
120			lang = lexer.Config().Name
121		}
122		if lang != "markdown" {
123			b = append(b, lineNo)
124		}
125		return b
126	default:
127		return []key.Binding{}
128	}
129}
130
131// FullHelp implements help.KeyMap.
132func (f *Files) FullHelp() [][]key.Binding {
133	b := make([][]key.Binding, 0)
134	switch f.activeView {
135	case filesViewFiles:
136		copyKey := f.common.KeyMap.Copy
137		copyKey.SetHelp("c", "copy name")
138		k := f.selector.KeyMap
139		b = append(b, []key.Binding{
140			f.common.KeyMap.SelectItem,
141			f.common.KeyMap.BackItem,
142		})
143		b = append(b, [][]key.Binding{
144			{
145				k.CursorUp,
146				k.CursorDown,
147				k.NextPage,
148				k.PrevPage,
149			},
150			{
151				k.GoToStart,
152				k.GoToEnd,
153				copyKey,
154			},
155		}...)
156	case filesViewContent:
157		copyKey := f.common.KeyMap.Copy
158		copyKey.SetHelp("c", "copy content")
159		k := f.code.KeyMap
160		b = append(b, []key.Binding{
161			f.common.KeyMap.BackItem,
162		})
163		b = append(b, [][]key.Binding{
164			{
165				k.PageDown,
166				k.PageUp,
167				k.HalfPageDown,
168				k.HalfPageUp,
169			},
170		}...)
171		lc := []key.Binding{
172			k.Down,
173			k.Up,
174			copyKey,
175		}
176		lexer := lexers.Match(f.currentContent.ext)
177		lang := ""
178		if lexer != nil && lexer.Config() != nil {
179			lang = lexer.Config().Name
180		}
181		if lang != "markdown" {
182			lc = append(lc, lineNo)
183		}
184		b = append(b, lc)
185	}
186	return b
187}
188
189// Init implements tea.Model.
190func (f *Files) Init() tea.Cmd {
191	f.path = ""
192	f.currentItem = nil
193	f.activeView = filesViewFiles
194	f.lastSelected = make([]int, 0)
195	f.selector.Select(0)
196	return f.updateFilesCmd
197}
198
199// Update implements tea.Model.
200func (f *Files) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
201	cmds := make([]tea.Cmd, 0)
202	switch msg := msg.(type) {
203	case RepoMsg:
204		f.repo = msg
205	case RefMsg:
206		f.ref = msg
207		cmds = append(cmds, f.Init())
208	case FileItemsMsg:
209		cmds = append(cmds,
210			f.selector.SetItems(msg),
211			updateStatusBarCmd,
212		)
213	case FileContentMsg:
214		f.activeView = filesViewContent
215		f.currentContent = msg
216		f.code.SetContent(msg.content, msg.ext)
217		f.code.GotoTop()
218		cmds = append(cmds, updateStatusBarCmd)
219	case selector.SelectMsg:
220		switch sel := msg.IdentifiableItem.(type) {
221		case FileItem:
222			f.currentItem = &sel
223			f.path = filepath.Join(f.path, sel.entry.Name())
224			if sel.entry.IsTree() {
225				cmds = append(cmds, f.selectTreeCmd)
226			} else {
227				cmds = append(cmds, f.selectFileCmd)
228			}
229		}
230	case BackMsg:
231		cmds = append(cmds, f.deselectItemCmd)
232	case tea.KeyMsg:
233		switch f.activeView {
234		case filesViewFiles:
235			switch {
236			case key.Matches(msg, f.common.KeyMap.SelectItem):
237				cmds = append(cmds, f.selector.SelectItem)
238			case key.Matches(msg, f.common.KeyMap.BackItem):
239				cmds = append(cmds, backCmd)
240			}
241		case filesViewContent:
242			switch {
243			case key.Matches(msg, f.common.KeyMap.BackItem):
244				cmds = append(cmds, backCmd)
245			case key.Matches(msg, f.common.KeyMap.Copy):
246				f.common.Copy.Copy(f.currentContent.content)
247			case key.Matches(msg, lineNo):
248				f.lineNumber = !f.lineNumber
249				f.code.SetShowLineNumber(f.lineNumber)
250				cmds = append(cmds, f.code.SetContent(f.currentContent.content, f.currentContent.ext))
251			}
252		}
253	case tea.WindowSizeMsg:
254		switch f.activeView {
255		case filesViewFiles:
256			if f.repo != nil {
257				cmds = append(cmds, f.updateFilesCmd)
258			}
259		case filesViewContent:
260			if f.currentContent.content != "" {
261				m, cmd := f.code.Update(msg)
262				f.code = m.(*code.Code)
263				if cmd != nil {
264					cmds = append(cmds, cmd)
265				}
266			}
267		}
268	case selector.ActiveMsg:
269		cmds = append(cmds, updateStatusBarCmd)
270	case EmptyRepoMsg:
271		f.ref = nil
272		f.path = ""
273		f.currentItem = nil
274		f.activeView = filesViewFiles
275		f.lastSelected = make([]int, 0)
276		f.selector.Select(0)
277		cmds = append(cmds, f.setItems([]selector.IdentifiableItem{}))
278	}
279	switch f.activeView {
280	case filesViewFiles:
281		m, cmd := f.selector.Update(msg)
282		f.selector = m.(*selector.Selector)
283		if cmd != nil {
284			cmds = append(cmds, cmd)
285		}
286	case filesViewContent:
287		m, cmd := f.code.Update(msg)
288		f.code = m.(*code.Code)
289		if cmd != nil {
290			cmds = append(cmds, cmd)
291		}
292	}
293	return f, tea.Batch(cmds...)
294}
295
296// View implements tea.Model.
297func (f *Files) View() string {
298	switch f.activeView {
299	case filesViewFiles:
300		return f.selector.View()
301	case filesViewContent:
302		return f.code.View()
303	default:
304		return ""
305	}
306}
307
308// StatusBarValue returns the status bar value.
309func (f *Files) StatusBarValue() string {
310	p := f.path
311	if p == "." {
312		// FIXME: this is a hack to force clear the status bar value
313		return " "
314	}
315	return p
316}
317
318// StatusBarInfo returns the status bar info.
319func (f *Files) StatusBarInfo() string {
320	switch f.activeView {
321	case filesViewFiles:
322		return fmt.Sprintf("# %d/%d", f.selector.Index()+1, len(f.selector.VisibleItems()))
323	case filesViewContent:
324		return fmt.Sprintf("☰ %.f%%", f.code.ScrollPercent()*100)
325	default:
326		return ""
327	}
328}
329
330func (f *Files) updateFilesCmd() tea.Msg {
331	files := make([]selector.IdentifiableItem, 0)
332	dirs := make([]selector.IdentifiableItem, 0)
333	if f.ref == nil {
334		log.Printf("ui: files: ref is nil")
335		return common.ErrorMsg(errNoRef)
336	}
337	r, err := f.repo.Open()
338	if err != nil {
339		return common.ErrorMsg(err)
340	}
341	t, err := r.TreePath(f.ref, f.path)
342	if err != nil {
343		log.Printf("ui: files: error getting tree %v", err)
344		return common.ErrorMsg(err)
345	}
346	ents, err := t.Entries()
347	if err != nil {
348		log.Printf("ui: files: error listing files %v", err)
349		return common.ErrorMsg(err)
350	}
351	ents.Sort()
352	for _, e := range ents {
353		if e.IsTree() {
354			dirs = append(dirs, FileItem{entry: e})
355		} else {
356			files = append(files, FileItem{entry: e})
357		}
358	}
359	return FileItemsMsg(append(dirs, files...))
360}
361
362func (f *Files) selectTreeCmd() tea.Msg {
363	if f.currentItem != nil && f.currentItem.entry.IsTree() {
364		f.lastSelected = append(f.lastSelected, f.selector.Index())
365		f.selector.Select(0)
366		return f.updateFilesCmd()
367	}
368	log.Printf("ui: files: current item is not a tree")
369	return common.ErrorMsg(errNoFileSelected)
370}
371
372func (f *Files) selectFileCmd() tea.Msg {
373	i := f.currentItem
374	if i != nil && !i.entry.IsTree() {
375		fi := i.entry.File()
376		if i.Mode().IsDir() || f == nil {
377			log.Printf("ui: files: current item is not a file")
378			return common.ErrorMsg(errInvalidFile)
379		}
380		bin, err := fi.IsBinary()
381		if err != nil {
382			f.path = filepath.Dir(f.path)
383			log.Printf("ui: files: error checking if file is binary %v", err)
384			return common.ErrorMsg(err)
385		}
386		if bin {
387			f.path = filepath.Dir(f.path)
388			log.Printf("ui: files: file is binary")
389			return common.ErrorMsg(errBinaryFile)
390		}
391		c, err := fi.Bytes()
392		if err != nil {
393			f.path = filepath.Dir(f.path)
394			log.Printf("ui: files: error reading file %v", err)
395			return common.ErrorMsg(err)
396		}
397		f.lastSelected = append(f.lastSelected, f.selector.Index())
398		return FileContentMsg{string(c), i.entry.Name()}
399	}
400	log.Printf("ui: files: current item is not a file")
401	return common.ErrorMsg(errNoFileSelected)
402}
403
404func (f *Files) deselectItemCmd() tea.Msg {
405	f.path = filepath.Dir(f.path)
406	f.activeView = filesViewFiles
407	msg := f.updateFilesCmd()
408	index := 0
409	if len(f.lastSelected) > 0 {
410		index = f.lastSelected[len(f.lastSelected)-1]
411		f.lastSelected = f.lastSelected[:len(f.lastSelected)-1]
412	}
413	f.selector.Select(index)
414	return msg
415}
416
417func (f *Files) setItems(items []selector.IdentifiableItem) tea.Cmd {
418	return func() tea.Msg {
419		return FileItemsMsg(items)
420	}
421}