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 }
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 log.Printf("ui: files: ref is nil")
324 return common.ErrorMsg(errNoRef)
325 }
326 t, err := f.repo.Repo.Repository().TreePath(f.ref, f.path)
327 if err != nil {
328 log.Printf("ui: files: error getting tree %v", err)
329 return common.ErrorMsg(err)
330 }
331 ents, err := t.Entries()
332 if err != nil {
333 log.Printf("ui: files: error listing files %v", err)
334 return common.ErrorMsg(err)
335 }
336 ents.Sort()
337 for _, e := range ents {
338 if e.IsTree() {
339 dirs = append(dirs, FileItem{entry: e})
340 } else {
341 files = append(files, FileItem{entry: e})
342 }
343 }
344 return FileItemsMsg(append(dirs, files...))
345}
346
347func (f *Files) selectTreeCmd() tea.Msg {
348 if f.currentItem != nil && f.currentItem.entry.IsTree() {
349 f.lastSelected = append(f.lastSelected, f.selector.Index())
350 f.selector.Select(0)
351 return f.updateFilesCmd()
352 }
353 log.Printf("ui: files: current item is not a tree")
354 return common.ErrorMsg(errNoFileSelected)
355}
356
357func (f *Files) selectFileCmd() tea.Msg {
358 i := f.currentItem
359 if i != nil && !i.entry.IsTree() {
360 fi := i.entry.File()
361 if i.Mode().IsDir() || f == nil {
362 log.Printf("ui: files: current item is not a file")
363 return common.ErrorMsg(errInvalidFile)
364 }
365 bin, err := fi.IsBinary()
366 if err != nil {
367 f.path = filepath.Dir(f.path)
368 log.Printf("ui: files: error checking if file is binary %v", err)
369 return common.ErrorMsg(err)
370 }
371 if bin {
372 f.path = filepath.Dir(f.path)
373 log.Printf("ui: files: file is binary")
374 return common.ErrorMsg(errBinaryFile)
375 }
376 c, err := fi.Bytes()
377 if err != nil {
378 f.path = filepath.Dir(f.path)
379 log.Printf("ui: files: error reading file %v", err)
380 return common.ErrorMsg(err)
381 }
382 f.lastSelected = append(f.lastSelected, f.selector.Index())
383 return FileContentMsg{string(c), i.entry.Name()}
384 }
385 log.Printf("ui: files: current item is not a file")
386 return common.ErrorMsg(errNoFileSelected)
387}
388
389func (f *Files) deselectItemCmd() tea.Msg {
390 f.path = filepath.Dir(f.path)
391 f.activeView = filesViewFiles
392 msg := f.updateFilesCmd()
393 index := 0
394 if len(f.lastSelected) > 0 {
395 index = f.lastSelected[len(f.lastSelected)-1]
396 f.lastSelected = f.lastSelected[:len(f.lastSelected)-1]
397 }
398 f.selector.Select(index)
399 return msg
400}