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	ggit "github.com/charmbracelet/soft-serve/git"
 13	"github.com/charmbracelet/soft-serve/ui/common"
 14	"github.com/charmbracelet/soft-serve/ui/components/code"
 15	"github.com/charmbracelet/soft-serve/ui/components/selector"
 16	"github.com/charmbracelet/soft-serve/ui/git"
 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            *ggit.Reference
 54	activeView     filesView
 55	repo           *git.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 EmptyRepoMsg:
269		f.ref = nil
270		f.path = ""
271		f.currentItem = nil
272		f.activeView = filesViewFiles
273		f.lastSelected = make([]int, 0)
274		f.selector.Select(0)
275		cmds = append(cmds, f.setItems([]selector.IdentifiableItem{}))
276	}
277	switch f.activeView {
278	case filesViewFiles:
279		m, cmd := f.selector.Update(msg)
280		f.selector = m.(*selector.Selector)
281		if cmd != nil {
282			cmds = append(cmds, cmd)
283		}
284	case filesViewContent:
285		m, cmd := f.code.Update(msg)
286		f.code = m.(*code.Code)
287		if cmd != nil {
288			cmds = append(cmds, cmd)
289		}
290	}
291	return f, tea.Batch(cmds...)
292}
293
294// View implements tea.Model.
295func (f *Files) View() string {
296	switch f.activeView {
297	case filesViewFiles:
298		return f.selector.View()
299	case filesViewContent:
300		return f.code.View()
301	default:
302		return ""
303	}
304}
305
306// StatusBarValue returns the status bar value.
307func (f *Files) StatusBarValue() string {
308	p := f.path
309	if p == "." {
310		return ""
311	}
312	return p
313}
314
315// StatusBarInfo returns the status bar info.
316func (f *Files) StatusBarInfo() string {
317	switch f.activeView {
318	case filesViewFiles:
319		return fmt.Sprintf("# %d/%d", f.selector.Index()+1, len(f.selector.VisibleItems()))
320	case filesViewContent:
321		return fmt.Sprintf("☰ %.f%%", f.code.ScrollPercent()*100)
322	default:
323		return ""
324	}
325}
326
327func (f *Files) updateFilesCmd() tea.Msg {
328	files := make([]selector.IdentifiableItem, 0)
329	dirs := make([]selector.IdentifiableItem, 0)
330	if f.ref == nil {
331		log.Printf("ui: files: ref is nil")
332		return common.ErrorMsg(errNoRef)
333	}
334	t, err := f.repo.Repo.Repository().TreePath(f.ref, f.path)
335	if err != nil {
336		log.Printf("ui: files: error getting tree %v", err)
337		return common.ErrorMsg(err)
338	}
339	ents, err := t.Entries()
340	if err != nil {
341		log.Printf("ui: files: error listing files %v", err)
342		return common.ErrorMsg(err)
343	}
344	ents.Sort()
345	for _, e := range ents {
346		if e.IsTree() {
347			dirs = append(dirs, FileItem{entry: e})
348		} else {
349			files = append(files, FileItem{entry: e})
350		}
351	}
352	return FileItemsMsg(append(dirs, files...))
353}
354
355func (f *Files) selectTreeCmd() tea.Msg {
356	if f.currentItem != nil && f.currentItem.entry.IsTree() {
357		f.lastSelected = append(f.lastSelected, f.selector.Index())
358		f.selector.Select(0)
359		return f.updateFilesCmd()
360	}
361	log.Printf("ui: files: current item is not a tree")
362	return common.ErrorMsg(errNoFileSelected)
363}
364
365func (f *Files) selectFileCmd() tea.Msg {
366	i := f.currentItem
367	if i != nil && !i.entry.IsTree() {
368		fi := i.entry.File()
369		if i.Mode().IsDir() || f == nil {
370			log.Printf("ui: files: current item is not a file")
371			return common.ErrorMsg(errInvalidFile)
372		}
373		bin, err := fi.IsBinary()
374		if err != nil {
375			f.path = filepath.Dir(f.path)
376			log.Printf("ui: files: error checking if file is binary %v", err)
377			return common.ErrorMsg(err)
378		}
379		if bin {
380			f.path = filepath.Dir(f.path)
381			log.Printf("ui: files: file is binary")
382			return common.ErrorMsg(errBinaryFile)
383		}
384		c, err := fi.Bytes()
385		if err != nil {
386			f.path = filepath.Dir(f.path)
387			log.Printf("ui: files: error reading file %v", err)
388			return common.ErrorMsg(err)
389		}
390		f.lastSelected = append(f.lastSelected, f.selector.Index())
391		return FileContentMsg{string(c), i.entry.Name()}
392	}
393	log.Printf("ui: files: current item is not a file")
394	return common.ErrorMsg(errNoFileSelected)
395}
396
397func (f *Files) deselectItemCmd() tea.Msg {
398	f.path = filepath.Dir(f.path)
399	f.activeView = filesViewFiles
400	msg := f.updateFilesCmd()
401	index := 0
402	if len(f.lastSelected) > 0 {
403		index = f.lastSelected[len(f.lastSelected)-1]
404		f.lastSelected = f.lastSelected[:len(f.lastSelected)-1]
405	}
406	f.selector.Select(index)
407	return msg
408}
409
410func (f *Files) setItems(items []selector.IdentifiableItem) tea.Cmd {
411	return func() tea.Msg {
412		return FileItemsMsg(items)
413	}
414}