sidebar.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package chat
  2. import (
  3. "context"
  4. "fmt"
  5. "sort"
  6. "strings"
  7. tea "github.com/charmbracelet/bubbletea"
  8. "github.com/charmbracelet/lipgloss"
  9. "github.com/kujtimiihoxha/opencode/internal/config"
  10. "github.com/kujtimiihoxha/opencode/internal/diff"
  11. "github.com/kujtimiihoxha/opencode/internal/history"
  12. "github.com/kujtimiihoxha/opencode/internal/pubsub"
  13. "github.com/kujtimiihoxha/opencode/internal/session"
  14. "github.com/kujtimiihoxha/opencode/internal/tui/styles"
  15. )
  16. type sidebarCmp struct {
  17. width, height int
  18. session session.Session
  19. history history.Service
  20. modFiles map[string]struct {
  21. additions int
  22. removals int
  23. }
  24. }
  25. func (m *sidebarCmp) Init() tea.Cmd {
  26. if m.history != nil {
  27. ctx := context.Background()
  28. // Subscribe to file events
  29. filesCh := m.history.Subscribe(ctx)
  30. // Initialize the modified files map
  31. m.modFiles = make(map[string]struct {
  32. additions int
  33. removals int
  34. })
  35. // Load initial files and calculate diffs
  36. m.loadModifiedFiles(ctx)
  37. // Return a command that will send file events to the Update method
  38. return func() tea.Msg {
  39. return <-filesCh
  40. }
  41. }
  42. return nil
  43. }
  44. func (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  45. switch msg := msg.(type) {
  46. case SessionSelectedMsg:
  47. if msg.ID != m.session.ID {
  48. m.session = msg
  49. ctx := context.Background()
  50. m.loadModifiedFiles(ctx)
  51. }
  52. case pubsub.Event[session.Session]:
  53. if msg.Type == pubsub.UpdatedEvent {
  54. if m.session.ID == msg.Payload.ID {
  55. m.session = msg.Payload
  56. }
  57. }
  58. case pubsub.Event[history.File]:
  59. if msg.Payload.SessionID == m.session.ID {
  60. // Process the individual file change instead of reloading all files
  61. ctx := context.Background()
  62. m.processFileChanges(ctx, msg.Payload)
  63. // Return a command to continue receiving events
  64. return m, func() tea.Msg {
  65. ctx := context.Background()
  66. filesCh := m.history.Subscribe(ctx)
  67. return <-filesCh
  68. }
  69. }
  70. }
  71. return m, nil
  72. }
  73. func (m *sidebarCmp) View() string {
  74. return styles.BaseStyle.
  75. Width(m.width).
  76. PaddingLeft(4).
  77. PaddingRight(2).
  78. Height(m.height - 1).
  79. Render(
  80. lipgloss.JoinVertical(
  81. lipgloss.Top,
  82. header(m.width),
  83. " ",
  84. m.sessionSection(),
  85. " ",
  86. lspsConfigured(m.width),
  87. " ",
  88. m.modifiedFiles(),
  89. ),
  90. )
  91. }
  92. func (m *sidebarCmp) sessionSection() string {
  93. sessionKey := styles.BaseStyle.Foreground(styles.PrimaryColor).Bold(true).Render("Session")
  94. sessionValue := styles.BaseStyle.
  95. Foreground(styles.Forground).
  96. Width(m.width - lipgloss.Width(sessionKey)).
  97. Render(fmt.Sprintf(": %s", m.session.Title))
  98. return lipgloss.JoinHorizontal(
  99. lipgloss.Left,
  100. sessionKey,
  101. sessionValue,
  102. )
  103. }
  104. func (m *sidebarCmp) modifiedFile(filePath string, additions, removals int) string {
  105. stats := ""
  106. if additions > 0 && removals > 0 {
  107. stats = styles.BaseStyle.Foreground(styles.ForgroundDim).Render(fmt.Sprintf(" %d additions and %d removals", additions, removals))
  108. } else if additions > 0 {
  109. stats = styles.BaseStyle.Foreground(styles.ForgroundDim).Render(fmt.Sprintf(" %d additions", additions))
  110. } else if removals > 0 {
  111. stats = styles.BaseStyle.Foreground(styles.ForgroundDim).Render(fmt.Sprintf(" %d removals", removals))
  112. }
  113. filePathStr := styles.BaseStyle.Foreground(styles.Forground).Render(filePath)
  114. return styles.BaseStyle.
  115. Width(m.width).
  116. Render(
  117. lipgloss.JoinHorizontal(
  118. lipgloss.Left,
  119. filePathStr,
  120. stats,
  121. ),
  122. )
  123. }
  124. func (m *sidebarCmp) modifiedFiles() string {
  125. modifiedFiles := styles.BaseStyle.Width(m.width).Foreground(styles.PrimaryColor).Bold(true).Render("Modified Files:")
  126. // If no modified files, show a placeholder message
  127. if m.modFiles == nil || len(m.modFiles) == 0 {
  128. message := "No modified files"
  129. remainingWidth := m.width - lipgloss.Width(message)
  130. if remainingWidth > 0 {
  131. message += strings.Repeat(" ", remainingWidth)
  132. }
  133. return styles.BaseStyle.
  134. Width(m.width).
  135. Render(
  136. lipgloss.JoinVertical(
  137. lipgloss.Top,
  138. modifiedFiles,
  139. styles.BaseStyle.Foreground(styles.ForgroundDim).Render(message),
  140. ),
  141. )
  142. }
  143. // Sort file paths alphabetically for consistent ordering
  144. var paths []string
  145. for path := range m.modFiles {
  146. paths = append(paths, path)
  147. }
  148. sort.Strings(paths)
  149. // Create views for each file in sorted order
  150. var fileViews []string
  151. for _, path := range paths {
  152. stats := m.modFiles[path]
  153. fileViews = append(fileViews, m.modifiedFile(path, stats.additions, stats.removals))
  154. }
  155. return styles.BaseStyle.
  156. Width(m.width).
  157. Render(
  158. lipgloss.JoinVertical(
  159. lipgloss.Top,
  160. modifiedFiles,
  161. lipgloss.JoinVertical(
  162. lipgloss.Left,
  163. fileViews...,
  164. ),
  165. ),
  166. )
  167. }
  168. func (m *sidebarCmp) SetSize(width, height int) tea.Cmd {
  169. m.width = width
  170. m.height = height
  171. return nil
  172. }
  173. func (m *sidebarCmp) GetSize() (int, int) {
  174. return m.width, m.height
  175. }
  176. func NewSidebarCmp(session session.Session, history history.Service) tea.Model {
  177. return &sidebarCmp{
  178. session: session,
  179. history: history,
  180. }
  181. }
  182. func (m *sidebarCmp) loadModifiedFiles(ctx context.Context) {
  183. if m.history == nil || m.session.ID == "" {
  184. return
  185. }
  186. // Get all latest files for this session
  187. latestFiles, err := m.history.ListLatestSessionFiles(ctx, m.session.ID)
  188. if err != nil {
  189. return
  190. }
  191. // Get all files for this session (to find initial versions)
  192. allFiles, err := m.history.ListBySession(ctx, m.session.ID)
  193. if err != nil {
  194. return
  195. }
  196. // Clear the existing map to rebuild it
  197. m.modFiles = make(map[string]struct {
  198. additions int
  199. removals int
  200. })
  201. // Process each latest file
  202. for _, file := range latestFiles {
  203. // Skip if this is the initial version (no changes to show)
  204. if file.Version == history.InitialVersion {
  205. continue
  206. }
  207. // Find the initial version for this specific file
  208. var initialVersion history.File
  209. for _, v := range allFiles {
  210. if v.Path == file.Path && v.Version == history.InitialVersion {
  211. initialVersion = v
  212. break
  213. }
  214. }
  215. // Skip if we can't find the initial version
  216. if initialVersion.ID == "" {
  217. continue
  218. }
  219. if initialVersion.Content == file.Content {
  220. continue
  221. }
  222. // Calculate diff between initial and latest version
  223. _, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)
  224. // Only add to modified files if there are changes
  225. if additions > 0 || removals > 0 {
  226. // Remove working directory prefix from file path
  227. displayPath := file.Path
  228. workingDir := config.WorkingDirectory()
  229. displayPath = strings.TrimPrefix(displayPath, workingDir)
  230. displayPath = strings.TrimPrefix(displayPath, "/")
  231. m.modFiles[displayPath] = struct {
  232. additions int
  233. removals int
  234. }{
  235. additions: additions,
  236. removals: removals,
  237. }
  238. }
  239. }
  240. }
  241. func (m *sidebarCmp) processFileChanges(ctx context.Context, file history.File) {
  242. // Skip if this is the initial version (no changes to show)
  243. if file.Version == history.InitialVersion {
  244. return
  245. }
  246. // Find the initial version for this file
  247. initialVersion, err := m.findInitialVersion(ctx, file.Path)
  248. if err != nil || initialVersion.ID == "" {
  249. return
  250. }
  251. // Skip if content hasn't changed
  252. if initialVersion.Content == file.Content {
  253. // If this file was previously modified but now matches the initial version,
  254. // remove it from the modified files list
  255. displayPath := getDisplayPath(file.Path)
  256. delete(m.modFiles, displayPath)
  257. return
  258. }
  259. // Calculate diff between initial and latest version
  260. _, additions, removals := diff.GenerateDiff(initialVersion.Content, file.Content, file.Path)
  261. // Only add to modified files if there are changes
  262. if additions > 0 || removals > 0 {
  263. displayPath := getDisplayPath(file.Path)
  264. m.modFiles[displayPath] = struct {
  265. additions int
  266. removals int
  267. }{
  268. additions: additions,
  269. removals: removals,
  270. }
  271. } else {
  272. // If no changes, remove from modified files
  273. displayPath := getDisplayPath(file.Path)
  274. delete(m.modFiles, displayPath)
  275. }
  276. }
  277. // Helper function to find the initial version of a file
  278. func (m *sidebarCmp) findInitialVersion(ctx context.Context, path string) (history.File, error) {
  279. // Get all versions of this file for the session
  280. fileVersions, err := m.history.ListBySession(ctx, m.session.ID)
  281. if err != nil {
  282. return history.File{}, err
  283. }
  284. // Find the initial version
  285. for _, v := range fileVersions {
  286. if v.Path == path && v.Version == history.InitialVersion {
  287. return v, nil
  288. }
  289. }
  290. return history.File{}, fmt.Errorf("initial version not found")
  291. }
  292. // Helper function to get the display path for a file
  293. func getDisplayPath(path string) string {
  294. workingDir := config.WorkingDirectory()
  295. displayPath := strings.TrimPrefix(path, workingDir)
  296. return strings.TrimPrefix(displayPath, "/")
  297. }