1package repo
  2
  3import (
  4	"errors"
  5	"fmt"
  6	"path/filepath"
  7
  8	"github.com/alecthomas/chroma/lexers"
  9	"github.com/charmbracelet/bubbles/key"
 10	tea "github.com/charmbracelet/bubbletea"
 11	ggit "github.com/charmbracelet/soft-serve/git"
 12	"github.com/charmbracelet/soft-serve/ui/common"
 13	"github.com/charmbracelet/soft-serve/ui/components/code"
 14	"github.com/charmbracelet/soft-serve/ui/components/selector"
 15	"github.com/charmbracelet/soft-serve/ui/git"
 16)
 17
 18type filesView int
 19
 20const (
 21	filesViewFiles filesView = iota
 22	filesViewContent
 23)
 24
 25var (
 26	errNoFileSelected = errors.New("no file selected")
 27	errBinaryFile     = errors.New("binary file")
 28	errFileTooLarge   = errors.New("file is too large")
 29	errInvalidFile    = errors.New("invalid file")
 30)
 31
 32var (
 33	lineNo = key.NewBinding(
 34		key.WithKeys("l"),
 35		key.WithHelp("l", "toggle line numbers"),
 36	)
 37)
 38
 39// FileItemsMsg is a message that contains a list of files.
 40type FileItemsMsg []selector.IdentifiableItem
 41
 42// FileContentMsg is a message that contains the content of a file.
 43type FileContentMsg struct {
 44	content string
 45	ext     string
 46}
 47
 48// Files is the model for the files view.
 49type Files struct {
 50	common         common.Common
 51	selector       *selector.Selector
 52	ref            *ggit.Reference
 53	activeView     filesView
 54	repo           git.GitRepo
 55	code           *code.Code
 56	path           string
 57	currentItem    *FileItem
 58	currentContent FileContentMsg
 59	lastSelected   []int
 60	lineNumber     bool
 61}
 62
 63// NewFiles creates a new files model.
 64func NewFiles(common common.Common) *Files {
 65	f := &Files{
 66		common:       common,
 67		code:         code.New(common, "", ""),
 68		activeView:   filesViewFiles,
 69		lastSelected: make([]int, 0),
 70		lineNumber:   true,
 71	}
 72	selector := selector.New(common, []selector.IdentifiableItem{}, FileItemDelegate{&common})
 73	selector.SetShowFilter(false)
 74	selector.SetShowHelp(false)
 75	selector.SetShowPagination(false)
 76	selector.SetShowStatusBar(false)
 77	selector.SetShowTitle(false)
 78	selector.SetFilteringEnabled(false)
 79	selector.DisableQuitKeybindings()
 80	selector.KeyMap.NextPage = common.KeyMap.NextPage
 81	selector.KeyMap.PrevPage = common.KeyMap.PrevPage
 82	f.selector = selector
 83	f.code.SetShowLineNumber(f.lineNumber)
 84	return f
 85}
 86
 87// SetSize implements common.Component.
 88func (f *Files) SetSize(width, height int) {
 89	f.common.SetSize(width, height)
 90	f.selector.SetSize(width, height)
 91	f.code.SetSize(width, height)
 92}
 93
 94// ShortHelp implements help.KeyMap.
 95func (f *Files) ShortHelp() []key.Binding {
 96	k := f.selector.KeyMap
 97	switch f.activeView {
 98	case filesViewFiles:
 99		copyKey := f.common.KeyMap.Copy
100		copyKey.SetHelp("c", "copy name")
101		return []key.Binding{
102			f.common.KeyMap.SelectItem,
103			f.common.KeyMap.BackItem,
104			k.CursorUp,
105			k.CursorDown,
106			copyKey,
107		}
108	case filesViewContent:
109		copyKey := f.common.KeyMap.Copy
110		copyKey.SetHelp("c", "copy content")
111		b := []key.Binding{
112			f.common.KeyMap.UpDown,
113			f.common.KeyMap.BackItem,
114			copyKey,
115		}
116		lexer := lexers.Match(f.currentContent.ext)
117		lang := ""
118		if lexer != nil && lexer.Config() != nil {
119			lang = lexer.Config().Name
120		}
121		if lang != "markdown" {
122			b = append(b, lineNo)
123		}
124		return b
125	default:
126		return []key.Binding{}
127	}
128}
129
130// FullHelp implements help.KeyMap.
131func (f *Files) FullHelp() [][]key.Binding {
132	b := make([][]key.Binding, 0)
133	switch f.activeView {
134	case filesViewFiles:
135		copyKey := f.common.KeyMap.Copy
136		copyKey.SetHelp("c", "copy name")
137		k := f.selector.KeyMap
138		b = append(b, []key.Binding{
139			f.common.KeyMap.SelectItem,
140			f.common.KeyMap.BackItem,
141		})
142		b = append(b, [][]key.Binding{
143			{
144				k.CursorUp,
145				k.CursorDown,
146				k.NextPage,
147				k.PrevPage,
148			},
149			{
150				k.GoToStart,
151				k.GoToEnd,
152				copyKey,
153			},
154		}...)
155	case filesViewContent:
156		copyKey := f.common.KeyMap.Copy
157		copyKey.SetHelp("c", "copy content")
158		k := f.code.KeyMap
159		b = append(b, []key.Binding{
160			f.common.KeyMap.BackItem,
161		})
162		b = append(b, [][]key.Binding{
163			{
164				k.PageDown,
165				k.PageUp,
166				k.HalfPageDown,
167				k.HalfPageUp,
168			},
169		}...)
170		lc := []key.Binding{
171			k.Down,
172			k.Up,
173			copyKey,
174		}
175		lexer := lexers.Match(f.currentContent.ext)
176		lang := ""
177		if lexer != nil && lexer.Config() != nil {
178			lang = lexer.Config().Name
179		}
180		if lang != "markdown" {
181			lc = append(lc, lineNo)
182		}
183		b = append(b, lc)
184	}
185	return b
186}
187
188// Init implements tea.Model.
189func (f *Files) Init() tea.Cmd {
190	f.path = ""
191	f.currentItem = nil
192	f.activeView = filesViewFiles
193	f.lastSelected = make([]int, 0)
194	f.selector.Select(0)
195	return f.updateFilesCmd
196}
197
198// Update implements tea.Model.
199func (f *Files) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
200	cmds := make([]tea.Cmd, 0)
201	switch msg := msg.(type) {
202	case RepoMsg:
203		f.repo = git.GitRepo(msg)
204		cmds = append(cmds, f.Init())
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	}
269	switch f.activeView {
270	case filesViewFiles:
271		m, cmd := f.selector.Update(msg)
272		f.selector = m.(*selector.Selector)
273		if cmd != nil {
274			cmds = append(cmds, cmd)
275		}
276	case filesViewContent:
277		m, cmd := f.code.Update(msg)
278		f.code = m.(*code.Code)
279		if cmd != nil {
280			cmds = append(cmds, cmd)
281		}
282	}
283	return f, tea.Batch(cmds...)
284}
285
286// View implements tea.Model.
287func (f *Files) View() string {
288	switch f.activeView {
289	case filesViewFiles:
290		return f.selector.View()
291	case filesViewContent:
292		return f.code.View()
293	default:
294		return ""
295	}
296}
297
298// StatusBarValue returns the status bar value.
299func (f *Files) StatusBarValue() string {
300	p := f.path
301	if p == "." {
302		return ""
303	}
304	return p
305}
306
307// StatusBarInfo returns the status bar info.
308func (f *Files) StatusBarInfo() string {
309	switch f.activeView {
310	case filesViewFiles:
311		return fmt.Sprintf("# %d/%d", f.selector.Index()+1, len(f.selector.VisibleItems()))
312	case filesViewContent:
313		return fmt.Sprintf("☰ %.f%%", f.code.ScrollPercent()*100)
314	default:
315		return ""
316	}
317}
318
319func (f *Files) updateFilesCmd() tea.Msg {
320	files := make([]selector.IdentifiableItem, 0)
321	dirs := make([]selector.IdentifiableItem, 0)
322	if f.ref == nil {
323		return common.ErrorMsg(errNoRef)
324	}
325	t, err := f.repo.Tree(f.ref, f.path)
326	if err != nil {
327		return common.ErrorMsg(err)
328	}
329	ents, err := t.Entries()
330	if err != nil {
331		return common.ErrorMsg(err)
332	}
333	ents.Sort()
334	for _, e := range ents {
335		if e.IsTree() {
336			dirs = append(dirs, FileItem{entry: e})
337		} else {
338			files = append(files, FileItem{entry: e})
339		}
340	}
341	return FileItemsMsg(append(dirs, files...))
342}
343
344func (f *Files) selectTreeCmd() tea.Msg {
345	if f.currentItem != nil && f.currentItem.entry.IsTree() {
346		f.lastSelected = append(f.lastSelected, f.selector.Index())
347		f.selector.Select(0)
348		return f.updateFilesCmd()
349	}
350	return common.ErrorMsg(errNoFileSelected)
351}
352
353func (f *Files) selectFileCmd() tea.Msg {
354	i := f.currentItem
355	if i != nil && !i.entry.IsTree() {
356		fi := i.entry.File()
357		if i.Mode().IsDir() || f == nil {
358			return common.ErrorMsg(errInvalidFile)
359		}
360		bin, err := fi.IsBinary()
361		if err != nil {
362			f.path = filepath.Dir(f.path)
363			return common.ErrorMsg(err)
364		}
365		if bin {
366			f.path = filepath.Dir(f.path)
367			return common.ErrorMsg(errBinaryFile)
368		}
369		c, err := fi.Bytes()
370		if err != nil {
371			f.path = filepath.Dir(f.path)
372			return common.ErrorMsg(err)
373		}
374		f.lastSelected = append(f.lastSelected, f.selector.Index())
375		return FileContentMsg{string(c), i.entry.Name()}
376	}
377	return common.ErrorMsg(errNoFileSelected)
378}
379
380func (f *Files) deselectItemCmd() tea.Msg {
381	f.path = filepath.Dir(f.path)
382	f.activeView = filesViewFiles
383	msg := f.updateFilesCmd()
384	index := 0
385	if len(f.lastSelected) > 0 {
386		index = f.lastSelected[len(f.lastSelected)-1]
387		f.lastSelected = f.lastSelected[:len(f.lastSelected)-1]
388	}
389	f.selector.Select(index)
390	return msg
391}