view.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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.guildsTree:
  129. v.focusMessageInput()
  130. case v.messagesList: // Handle both a.messagesList and a.flex as well as other edge cases (if there is).
  131. if ok := v.focusGuildsTree(); !ok {
  132. v.app.SetFocus(v.messageInput)
  133. }
  134. case v.messageInput:
  135. v.app.SetFocus(v.messagesList)
  136. }
  137. }
  138. func (v *View) focusNext() {
  139. switch v.app.GetFocus() {
  140. case v.guildsTree:
  141. v.app.SetFocus(v.messagesList)
  142. case v.messagesList:
  143. v.focusMessageInput()
  144. case v.messageInput: // Handle both a.messageInput and a.flex as well as other edge cases (if there is).
  145. if ok := v.focusGuildsTree(); !ok {
  146. v.app.SetFocus(v.messagesList)
  147. }
  148. }
  149. }
  150. func (v *View) onInputCapture(event *tcell.EventKey) *tcell.EventKey {
  151. switch event.Name() {
  152. case v.cfg.Keys.FocusGuildsTree:
  153. v.messageInput.removeMentionsList()
  154. v.focusGuildsTree()
  155. return nil
  156. case v.cfg.Keys.FocusMessagesList:
  157. v.messageInput.removeMentionsList()
  158. v.app.SetFocus(v.messagesList)
  159. return nil
  160. case v.cfg.Keys.FocusMessageInput:
  161. v.focusMessageInput()
  162. return nil
  163. case v.cfg.Keys.FocusPrevious:
  164. v.focusPrevious()
  165. return nil
  166. case v.cfg.Keys.FocusNext:
  167. v.focusNext()
  168. return nil
  169. case v.cfg.Keys.Logout:
  170. if v.onLogout != nil {
  171. v.onLogout()
  172. }
  173. if err := keyring.DeleteToken(); err != nil {
  174. slog.Error("failed to delete token from keyring", "err", err)
  175. return nil
  176. }
  177. return nil
  178. case v.cfg.Keys.ToggleGuildsTree:
  179. v.toggleGuildsTree()
  180. return nil
  181. case v.cfg.Keys.Picker.Toggle:
  182. v.togglePicker()
  183. return nil
  184. }
  185. return event
  186. }
  187. func (v *View) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  188. previousFocus := v.app.GetFocus()
  189. modal := tview.NewModal().
  190. SetText(prompt).
  191. AddButtons(buttons).
  192. SetDoneFunc(func(_ int, buttonLabel string) {
  193. v.RemovePage(confirmModalPageName).SwitchToPage(flexPageName)
  194. v.app.SetFocus(previousFocus)
  195. if onDone != nil {
  196. onDone(buttonLabel)
  197. }
  198. })
  199. v.
  200. AddAndSwitchToPage(confirmModalPageName, ui.Centered(modal, 0, 0), true).
  201. ShowPage(flexPageName)
  202. }
  203. func (v *View) onReadUpdate(event *read.UpdateEvent) {
  204. var guildNode *tview.TreeNode
  205. v.guildsTree.
  206. GetRoot().
  207. Walk(func(node, parent *tview.TreeNode) bool {
  208. switch node.GetReference() {
  209. case event.GuildID:
  210. node.SetTextStyle(v.guildsTree.getGuildNodeStyle(event.GuildID))
  211. guildNode = node
  212. return false
  213. case event.ChannelID:
  214. // private channel
  215. if !event.GuildID.IsValid() {
  216. style := v.guildsTree.getChannelNodeStyle(event.ChannelID)
  217. node.SetTextStyle(style)
  218. return false
  219. }
  220. }
  221. return true
  222. })
  223. if guildNode != nil {
  224. guildNode.Walk(func(node, parent *tview.TreeNode) bool {
  225. if node.GetReference() == event.ChannelID {
  226. node.SetTextStyle(v.guildsTree.getChannelNodeStyle(event.ChannelID))
  227. return false
  228. }
  229. return true
  230. })
  231. }
  232. v.app.Draw()
  233. }
  234. func (v *View) clearTypers() {
  235. v.typersMu.Lock()
  236. for _, timer := range v.typers {
  237. timer.Stop()
  238. }
  239. clear(v.typers)
  240. v.typersMu.Unlock()
  241. v.updateFooter()
  242. }
  243. func (v *View) addTyper(userID discord.UserID) {
  244. v.typersMu.Lock()
  245. typer, ok := v.typers[userID]
  246. if ok {
  247. typer.Reset(typingDuration)
  248. } else {
  249. v.typers[userID] = time.AfterFunc(typingDuration, func() {
  250. v.removeTyper(userID)
  251. })
  252. }
  253. v.typersMu.Unlock()
  254. v.updateFooter()
  255. }
  256. func (v *View) removeTyper(userID discord.UserID) {
  257. v.typersMu.Lock()
  258. if typer, ok := v.typers[userID]; ok {
  259. typer.Stop()
  260. delete(v.typers, userID)
  261. }
  262. v.typersMu.Unlock()
  263. v.updateFooter()
  264. }
  265. func (v *View) updateFooter() {
  266. selectedChannel := v.SelectedChannel()
  267. if selectedChannel == nil {
  268. return
  269. }
  270. guildID := selectedChannel.GuildID
  271. v.typersMu.RLock()
  272. defer v.typersMu.RUnlock()
  273. var footer string
  274. if len(v.typers) > 0 {
  275. var names []string
  276. for userID := range v.typers {
  277. var name string
  278. if guildID.IsValid() {
  279. member, err := v.state.Cabinet.Member(guildID, userID)
  280. if err != nil {
  281. slog.Error("failed to get member from state", "err", err, "guild_id", guildID, "user_id", userID)
  282. continue
  283. }
  284. if member.Nick != "" {
  285. name = member.Nick
  286. } else {
  287. name = member.User.DisplayOrUsername()
  288. }
  289. } else {
  290. for _, recipient := range selectedChannel.DMRecipients {
  291. if recipient.ID == userID {
  292. name = recipient.DisplayOrUsername()
  293. break
  294. }
  295. }
  296. }
  297. if name != "" {
  298. names = append(names, name)
  299. }
  300. }
  301. switch len(names) {
  302. case 1:
  303. footer = fmt.Sprintf("%s is typing...", names[0])
  304. case 2:
  305. footer = fmt.Sprintf("%s and %s are typing...", names[0], names[1])
  306. case 3:
  307. footer = fmt.Sprintf("%s, %s, and %s are typing...", names[0], names[1], names[2])
  308. default:
  309. footer = "Several people are typing..."
  310. }
  311. }
  312. go v.app.QueueUpdateDraw(func() { v.messagesList.SetFooter(footer) })
  313. }