view.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "sync"
  6. "time"
  7. "github.com/ayn2op/discordo/internal/config"
  8. "github.com/ayn2op/discordo/internal/keyring"
  9. "github.com/ayn2op/discordo/internal/ui"
  10. "github.com/ayn2op/tview"
  11. "github.com/diamondburned/arikawa/v3/discord"
  12. "github.com/diamondburned/ningen/v3"
  13. "github.com/diamondburned/ningen/v3/states/read"
  14. "github.com/gdamore/tcell/v3"
  15. )
  16. const typingDuration = 10 * time.Second
  17. const (
  18. flexPageName = "flex"
  19. mentionsListPageName = "mentionsList"
  20. attachmentsListPageName = "attachmentsList"
  21. confirmModalPageName = "confirmModal"
  22. channelsPickerPageName = "channelsPicker"
  23. )
  24. type View struct {
  25. *tview.Pages
  26. mainFlex *tview.Flex
  27. rightFlex *tview.Flex
  28. guildsTree *guildsTree
  29. messagesList *messagesList
  30. messageInput *messageInput
  31. channelsPicker *channelsPicker
  32. selectedChannel *discord.Channel
  33. selectedChannelMu sync.RWMutex
  34. typersMu sync.RWMutex
  35. typers map[discord.UserID]*time.Timer
  36. app *tview.Application
  37. cfg *config.Config
  38. state *ningen.State
  39. onLogout func()
  40. }
  41. func NewView(app *tview.Application, cfg *config.Config, onLogout func()) *View {
  42. v := &View{
  43. Pages: tview.NewPages(),
  44. mainFlex: tview.NewFlex(),
  45. rightFlex: tview.NewFlex(),
  46. typers: make(map[discord.UserID]*time.Timer),
  47. app: app,
  48. cfg: cfg,
  49. onLogout: onLogout,
  50. }
  51. v.guildsTree = newGuildsTree(cfg, v)
  52. v.messagesList = newMessagesList(cfg, v)
  53. v.messageInput = newMessageInput(cfg, v)
  54. v.channelsPicker = newChannelsPicker(cfg, v)
  55. v.channelsPicker.SetCancelFunc(v.closePicker)
  56. v.SetInputCapture(v.onInputCapture)
  57. v.buildLayout()
  58. return v
  59. }
  60. func (v *View) SelectedChannel() *discord.Channel {
  61. v.selectedChannelMu.RLock()
  62. defer v.selectedChannelMu.RUnlock()
  63. return v.selectedChannel
  64. }
  65. func (v *View) SetSelectedChannel(channel *discord.Channel) {
  66. v.selectedChannelMu.Lock()
  67. v.selectedChannel = channel
  68. v.selectedChannelMu.Unlock()
  69. }
  70. func (v *View) buildLayout() {
  71. v.Clear()
  72. v.rightFlex.Clear()
  73. v.mainFlex.Clear()
  74. v.rightFlex.
  75. SetDirection(tview.FlexRow).
  76. AddItem(v.messagesList, 0, 1, false).
  77. AddItem(v.messageInput, 3, 1, false)
  78. // The guilds tree is always focused first at start-up.
  79. v.mainFlex.
  80. AddItem(v.guildsTree, 0, 1, true).
  81. AddItem(v.rightFlex, 0, 4, false)
  82. v.AddAndSwitchToPage(flexPageName, v.mainFlex, true)
  83. }
  84. func (v *View) togglePicker() {
  85. if v.HasPage(channelsPickerPageName) {
  86. v.closePicker()
  87. } else {
  88. v.openPicker()
  89. }
  90. }
  91. func (v *View) openPicker() {
  92. v.AddAndSwitchToPage(channelsPickerPageName, ui.Centered(v.channelsPicker, v.cfg.Picker.Width, v.cfg.Picker.Height), true).ShowPage(flexPageName)
  93. v.channelsPicker.update()
  94. }
  95. func (v *View) closePicker() {
  96. v.RemovePage(channelsPickerPageName).SwitchToPage(flexPageName)
  97. v.channelsPicker.Update()
  98. }
  99. func (v *View) toggleGuildsTree() {
  100. // The guilds tree is visible if the number of items is two.
  101. if v.mainFlex.GetItemCount() == 2 {
  102. v.mainFlex.RemoveItem(v.guildsTree)
  103. if v.guildsTree.HasFocus() {
  104. v.app.SetFocus(v.mainFlex)
  105. }
  106. } else {
  107. v.buildLayout()
  108. v.app.SetFocus(v.guildsTree)
  109. }
  110. }
  111. func (v *View) focusGuildsTree() bool {
  112. // The guilds tree is not hidden if the number of items is two.
  113. if v.mainFlex.GetItemCount() == 2 {
  114. v.app.SetFocus(v.guildsTree)
  115. return true
  116. }
  117. return false
  118. }
  119. func (v *View) focusMessageInput() bool {
  120. if !v.messageInput.GetDisabled() {
  121. v.app.SetFocus(v.messageInput)
  122. return true
  123. }
  124. return false
  125. }
  126. func (v *View) focusPrevious() {
  127. switch v.app.GetFocus() {
  128. case v.messagesList: // Handle both a.messagesList and a.flex as well as other edge cases (if there is).
  129. if v.focusGuildsTree() {
  130. return
  131. }
  132. fallthrough
  133. case v.guildsTree:
  134. if v.focusMessageInput() {
  135. return
  136. }
  137. fallthrough
  138. case v.messageInput:
  139. v.app.SetFocus(v.messagesList)
  140. }
  141. }
  142. func (v *View) focusNext() {
  143. switch v.app.GetFocus() {
  144. case v.messagesList:
  145. if v.focusMessageInput() {
  146. return
  147. }
  148. fallthrough
  149. case v.messageInput: // Handle both a.messageInput and a.flex as well as other edge cases (if there is).
  150. if v.focusGuildsTree() {
  151. return
  152. }
  153. fallthrough
  154. case v.guildsTree:
  155. v.app.SetFocus(v.messagesList)
  156. }
  157. }
  158. func (v *View) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  159. switch event.Name() {
  160. case v.cfg.Keybinds.FocusGuildsTree:
  161. v.messageInput.removeMentionsList()
  162. v.focusGuildsTree()
  163. return nil
  164. case v.cfg.Keybinds.FocusMessagesList:
  165. v.messageInput.removeMentionsList()
  166. v.app.SetFocus(v.messagesList)
  167. return nil
  168. case v.cfg.Keybinds.FocusMessageInput:
  169. v.focusMessageInput()
  170. return nil
  171. case v.cfg.Keybinds.FocusPrevious:
  172. v.focusPrevious()
  173. return nil
  174. case v.cfg.Keybinds.FocusNext:
  175. v.focusNext()
  176. return nil
  177. case v.cfg.Keybinds.Logout:
  178. if v.onLogout != nil {
  179. v.onLogout()
  180. }
  181. if err := keyring.DeleteToken(); err != nil {
  182. slog.Error("failed to delete token from keyring", "err", err)
  183. return nil
  184. }
  185. return nil
  186. case v.cfg.Keybinds.ToggleGuildsTree:
  187. v.toggleGuildsTree()
  188. return nil
  189. case v.cfg.Keybinds.Picker.Toggle:
  190. v.togglePicker()
  191. return nil
  192. }
  193. return event
  194. }
  195. func (v *View) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  196. previousFocus := v.app.GetFocus()
  197. modal := tview.NewModal().
  198. SetText(prompt).
  199. AddButtons(buttons).
  200. SetDoneFunc(func(_ int, buttonLabel string) {
  201. v.RemovePage(confirmModalPageName).SwitchToPage(flexPageName)
  202. v.app.SetFocus(previousFocus)
  203. if onDone != nil {
  204. onDone(buttonLabel)
  205. }
  206. })
  207. v.
  208. AddAndSwitchToPage(confirmModalPageName, ui.Centered(modal, 0, 0), true).
  209. ShowPage(flexPageName)
  210. }
  211. func (v *View) onReadUpdate(event *read.UpdateEvent) {
  212. var guildNode *tview.TreeNode
  213. v.guildsTree.
  214. GetRoot().
  215. Walk(func(node, parent *tview.TreeNode) bool {
  216. switch node.GetReference() {
  217. case event.GuildID:
  218. node.SetTextStyle(v.guildsTree.getGuildNodeStyle(event.GuildID))
  219. guildNode = node
  220. return false
  221. case event.ChannelID:
  222. // private channel
  223. if !event.GuildID.IsValid() {
  224. style := v.guildsTree.getChannelNodeStyle(event.ChannelID)
  225. node.SetTextStyle(style)
  226. return false
  227. }
  228. }
  229. return true
  230. })
  231. if guildNode != nil {
  232. guildNode.Walk(func(node, parent *tview.TreeNode) bool {
  233. if node.GetReference() == event.ChannelID {
  234. node.SetTextStyle(v.guildsTree.getChannelNodeStyle(event.ChannelID))
  235. return false
  236. }
  237. return true
  238. })
  239. }
  240. v.app.Draw()
  241. }
  242. func (v *View) clearTypers() {
  243. v.typersMu.Lock()
  244. for _, timer := range v.typers {
  245. timer.Stop()
  246. }
  247. clear(v.typers)
  248. v.typersMu.Unlock()
  249. v.updateFooter()
  250. }
  251. func (v *View) addTyper(userID discord.UserID) {
  252. v.typersMu.Lock()
  253. typer, ok := v.typers[userID]
  254. if ok {
  255. typer.Reset(typingDuration)
  256. } else {
  257. v.typers[userID] = time.AfterFunc(typingDuration, func() {
  258. v.removeTyper(userID)
  259. })
  260. }
  261. v.typersMu.Unlock()
  262. v.updateFooter()
  263. }
  264. func (v *View) removeTyper(userID discord.UserID) {
  265. v.typersMu.Lock()
  266. if typer, ok := v.typers[userID]; ok {
  267. typer.Stop()
  268. delete(v.typers, userID)
  269. }
  270. v.typersMu.Unlock()
  271. v.updateFooter()
  272. }
  273. func (v *View) updateFooter() {
  274. selectedChannel := v.SelectedChannel()
  275. if selectedChannel == nil {
  276. return
  277. }
  278. guildID := selectedChannel.GuildID
  279. v.typersMu.RLock()
  280. defer v.typersMu.RUnlock()
  281. var footer string
  282. if len(v.typers) > 0 {
  283. var names []string
  284. for userID := range v.typers {
  285. var name string
  286. if guildID.IsValid() {
  287. member, err := v.state.Cabinet.Member(guildID, userID)
  288. if err != nil {
  289. slog.Error("failed to get member from state", "err", err, "guild_id", guildID, "user_id", userID)
  290. continue
  291. }
  292. if member.Nick != "" {
  293. name = member.Nick
  294. } else {
  295. name = member.User.DisplayOrUsername()
  296. }
  297. } else {
  298. for _, recipient := range selectedChannel.DMRecipients {
  299. if recipient.ID == userID {
  300. name = recipient.DisplayOrUsername()
  301. break
  302. }
  303. }
  304. }
  305. if name != "" {
  306. names = append(names, name)
  307. }
  308. }
  309. switch len(names) {
  310. case 1:
  311. footer = fmt.Sprintf("%s is typing...", names[0])
  312. case 2:
  313. footer = fmt.Sprintf("%s and %s are typing...", names[0], names[1])
  314. case 3:
  315. footer = fmt.Sprintf("%s, %s, and %s are typing...", names[0], names[1], names[2])
  316. default:
  317. footer = "Several people are typing..."
  318. }
  319. }
  320. go v.app.QueueUpdateDraw(func() { v.messagesList.SetFooter(footer) })
  321. }