model.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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/ui"
  9. "github.com/ayn2op/tview"
  10. "github.com/ayn2op/tview/flex"
  11. "github.com/ayn2op/tview/keybind"
  12. "github.com/ayn2op/tview/layers"
  13. "github.com/diamondburned/arikawa/v3/discord"
  14. "github.com/diamondburned/ningen/v3"
  15. "github.com/diamondburned/ningen/v3/states/read"
  16. "github.com/gdamore/tcell/v3"
  17. )
  18. const typingDuration = 10 * time.Second
  19. const (
  20. flexLayerName = "flex"
  21. mentionsListLayerName = "mentionsList"
  22. attachmentsListLayerName = "attachmentsList"
  23. confirmModalLayerName = "confirmModal"
  24. channelsPickerLayerName = "channelsPicker"
  25. )
  26. type Model struct {
  27. *layers.Layers
  28. // guildsTree (sidebar) + rightFlex
  29. mainFlex *flex.Model
  30. // messagesList + messageInput
  31. rightFlex *flex.Model
  32. guildsTree *guildsTree
  33. messagesList *messagesList
  34. messageInput *messageInput
  35. channelsPicker *channelsPicker
  36. selectedChannel *discord.Channel
  37. selectedChannelMu sync.RWMutex
  38. typersMu sync.RWMutex
  39. typers map[discord.UserID]*time.Timer
  40. confirmModalDone func(label string)
  41. confirmModalPreviousFocus tview.Primitive
  42. app *tview.Application
  43. cfg *config.Config
  44. state *ningen.State
  45. token string
  46. }
  47. func NewView(app *tview.Application, cfg *config.Config, token string) *Model {
  48. v := &Model{
  49. Layers: layers.New(),
  50. mainFlex: flex.NewModel(),
  51. rightFlex: flex.NewModel(),
  52. typers: make(map[discord.UserID]*time.Timer),
  53. app: app,
  54. cfg: cfg,
  55. token: token,
  56. }
  57. v.guildsTree = newGuildsTree(cfg, v)
  58. v.messagesList = newMessagesList(cfg, v)
  59. v.messageInput = newMessageInput(cfg, v)
  60. v.channelsPicker = newChannelsPicker(cfg, v)
  61. v.channelsPicker.SetCancelFunc(v.closePicker)
  62. v.SetBackgroundLayerStyle(v.cfg.Theme.Dialog.BackgroundStyle.Style)
  63. v.buildLayout()
  64. return v
  65. }
  66. func (m *Model) SelectedChannel() *discord.Channel {
  67. m.selectedChannelMu.RLock()
  68. defer m.selectedChannelMu.RUnlock()
  69. return m.selectedChannel
  70. }
  71. func (m *Model) SetSelectedChannel(channel *discord.Channel) {
  72. m.selectedChannelMu.Lock()
  73. m.selectedChannel = channel
  74. m.selectedChannelMu.Unlock()
  75. }
  76. func (m *Model) buildLayout() {
  77. m.Clear()
  78. m.rightFlex.Clear()
  79. m.mainFlex.Clear()
  80. m.rightFlex.
  81. SetDirection(flex.DirectionRow).
  82. AddItem(m.messagesList, 0, 1, false).
  83. AddItem(m.messageInput, 3, 1, false)
  84. // The guilds tree is always focused first at start-up.
  85. m.mainFlex.
  86. AddItem(m.guildsTree, 0, 1, true).
  87. AddItem(m.rightFlex, 0, 4, false)
  88. m.AddLayer(m.mainFlex, layers.WithName(flexLayerName), layers.WithResize(true), layers.WithVisible(true))
  89. m.AddLayer(m.messageInput.mentionsList, layers.WithName(mentionsListLayerName), layers.WithResize(false), layers.WithVisible(false))
  90. }
  91. func (m *Model) togglePicker() {
  92. if m.HasLayer(channelsPickerLayerName) {
  93. m.closePicker()
  94. } else {
  95. m.openPicker()
  96. }
  97. }
  98. func (m *Model) openPicker() {
  99. m.AddLayer(
  100. ui.Centered(m.channelsPicker, m.cfg.Picker.Width, m.cfg.Picker.Height),
  101. layers.WithName(channelsPickerLayerName),
  102. layers.WithResize(true),
  103. layers.WithVisible(true),
  104. layers.WithOverlay(),
  105. ).SendToFront(channelsPickerLayerName)
  106. m.channelsPicker.update()
  107. }
  108. func (m *Model) closePicker() {
  109. m.RemoveLayer(channelsPickerLayerName)
  110. m.channelsPicker.Update()
  111. }
  112. func (m *Model) toggleGuildsTree() {
  113. // The guilds tree is visible if the number of items is two.
  114. if m.mainFlex.GetItemCount() == 2 {
  115. m.mainFlex.RemoveItem(m.guildsTree)
  116. if m.guildsTree.HasFocus() {
  117. m.app.SetFocus(m.mainFlex)
  118. }
  119. } else {
  120. m.buildLayout()
  121. m.app.SetFocus(m.guildsTree)
  122. }
  123. }
  124. func (m *Model) focusGuildsTree() bool {
  125. // The guilds tree is not hidden if the number of items is two.
  126. if m.mainFlex.GetItemCount() == 2 {
  127. m.app.SetFocus(m.guildsTree)
  128. return true
  129. }
  130. return false
  131. }
  132. func (m *Model) focusMessageInput() bool {
  133. if !m.messageInput.GetDisabled() {
  134. m.app.SetFocus(m.messageInput)
  135. return true
  136. }
  137. return false
  138. }
  139. func (m *Model) focusPrevious() {
  140. switch m.app.Focused() {
  141. case m.messagesList: // Handle both a.messagesList and a.flex as well as other edge cases (if there is).
  142. if m.focusGuildsTree() {
  143. return
  144. }
  145. fallthrough
  146. case m.guildsTree:
  147. if m.focusMessageInput() {
  148. return
  149. }
  150. fallthrough
  151. case m.messageInput:
  152. m.app.SetFocus(m.messagesList)
  153. }
  154. }
  155. func (m *Model) focusNext() {
  156. switch m.app.Focused() {
  157. case m.messagesList:
  158. if m.focusMessageInput() {
  159. return
  160. }
  161. fallthrough
  162. case m.messageInput: // Handle both a.messageInput and a.flex as well as other edge cases (if there is).
  163. if m.focusGuildsTree() {
  164. return
  165. }
  166. fallthrough
  167. case m.guildsTree:
  168. m.app.SetFocus(m.messagesList)
  169. }
  170. }
  171. func (m *Model) HandleEvent(event tcell.Event) tview.Command {
  172. switch event := event.(type) {
  173. case *tview.InitEvent:
  174. return func() tcell.Event {
  175. if err := m.OpenState(m.token); err != nil {
  176. slog.Error("failed to open chat state", "err", err)
  177. return tcell.NewEventError(err)
  178. }
  179. return nil
  180. }
  181. case *QuitEvent:
  182. return tview.Batch(
  183. m.closeState(),
  184. tview.Quit(),
  185. )
  186. case *tview.ModalDoneEvent:
  187. if m.HasLayer(confirmModalLayerName) {
  188. m.RemoveLayer(confirmModalLayerName)
  189. if m.confirmModalPreviousFocus != nil {
  190. m.app.SetFocus(m.confirmModalPreviousFocus)
  191. }
  192. onDone := m.confirmModalDone
  193. m.confirmModalDone = nil
  194. m.confirmModalPreviousFocus = nil
  195. if onDone != nil {
  196. onDone(event.ButtonLabel)
  197. }
  198. return nil
  199. }
  200. case *tview.KeyEvent:
  201. switch {
  202. case keybind.Matches(event, m.cfg.Keybinds.FocusGuildsTree.Keybind):
  203. m.messageInput.removeMentionsList()
  204. m.focusGuildsTree()
  205. return nil
  206. case keybind.Matches(event, m.cfg.Keybinds.FocusMessagesList.Keybind):
  207. m.messageInput.removeMentionsList()
  208. m.app.SetFocus(m.messagesList)
  209. return nil
  210. case keybind.Matches(event, m.cfg.Keybinds.FocusMessageInput.Keybind):
  211. m.focusMessageInput()
  212. return nil
  213. case keybind.Matches(event, m.cfg.Keybinds.FocusPrevious.Keybind):
  214. m.focusPrevious()
  215. return nil
  216. case keybind.Matches(event, m.cfg.Keybinds.FocusNext.Keybind):
  217. m.focusNext()
  218. return nil
  219. case keybind.Matches(event, m.cfg.Keybinds.Logout.Keybind):
  220. return tview.Batch(m.closeState(), m.logout())
  221. case keybind.Matches(event, m.cfg.Keybinds.ToggleGuildsTree.Keybind):
  222. m.toggleGuildsTree()
  223. return nil
  224. case keybind.Matches(event, m.cfg.Keybinds.ToggleChannelsPicker.Keybind):
  225. m.togglePicker()
  226. return nil
  227. }
  228. case *closeLayerEvent:
  229. if m.HasLayer(event.name) {
  230. m.HideLayer(event.name)
  231. }
  232. return nil
  233. }
  234. return m.Layers.HandleEvent(event)
  235. }
  236. func (m *Model) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  237. m.confirmModalPreviousFocus = m.app.Focused()
  238. m.confirmModalDone = onDone
  239. modal := tview.NewModal().
  240. SetText(prompt).
  241. AddButtons(buttons)
  242. m.
  243. AddLayer(
  244. ui.Centered(modal, 0, 0),
  245. layers.WithName(confirmModalLayerName),
  246. layers.WithResize(true),
  247. layers.WithVisible(true),
  248. layers.WithOverlay(),
  249. ).
  250. SendToFront(confirmModalLayerName)
  251. }
  252. func (m *Model) onReadUpdate(event *read.UpdateEvent) {
  253. m.app.QueueUpdateDraw(func() {
  254. // Use indexed node lookup to avoid walking the whole tree on every read
  255. // event. This runs frequently while reading/typing across channels.
  256. if event.GuildID.IsValid() {
  257. if guildNode := m.guildsTree.findNodeByReference(event.GuildID); guildNode != nil {
  258. m.guildsTree.setNodeLineStyle(guildNode, m.guildsTree.getGuildNodeStyle(event.GuildID))
  259. }
  260. }
  261. // Channel style is always updated for the target channel regardless of
  262. // whether it's in a guild or DM.
  263. if channelNode := m.guildsTree.findNodeByReference(event.ChannelID); channelNode != nil {
  264. m.guildsTree.setNodeLineStyle(channelNode, m.guildsTree.getChannelNodeStyle(event.ChannelID))
  265. }
  266. })
  267. }
  268. func (m *Model) clearTypers() {
  269. m.typersMu.Lock()
  270. for _, timer := range m.typers {
  271. timer.Stop()
  272. }
  273. clear(m.typers)
  274. m.typersMu.Unlock()
  275. m.updateFooter()
  276. }
  277. func (m *Model) addTyper(userID discord.UserID) {
  278. m.typersMu.Lock()
  279. typer, ok := m.typers[userID]
  280. if ok {
  281. typer.Reset(typingDuration)
  282. } else {
  283. m.typers[userID] = time.AfterFunc(typingDuration, func() {
  284. m.removeTyper(userID)
  285. })
  286. }
  287. m.typersMu.Unlock()
  288. m.updateFooter()
  289. }
  290. func (m *Model) removeTyper(userID discord.UserID) {
  291. m.typersMu.Lock()
  292. if typer, ok := m.typers[userID]; ok {
  293. typer.Stop()
  294. delete(m.typers, userID)
  295. }
  296. m.typersMu.Unlock()
  297. m.updateFooter()
  298. }
  299. func (m *Model) updateFooter() {
  300. selectedChannel := m.SelectedChannel()
  301. if selectedChannel == nil {
  302. return
  303. }
  304. guildID := selectedChannel.GuildID
  305. m.typersMu.RLock()
  306. defer m.typersMu.RUnlock()
  307. var footer string
  308. if len(m.typers) > 0 {
  309. var names []string
  310. for userID := range m.typers {
  311. var name string
  312. if guildID.IsValid() {
  313. member, err := m.state.Cabinet.Member(guildID, userID)
  314. if err != nil {
  315. slog.Error("failed to get member from state", "err", err, "guild_id", guildID, "user_id", userID)
  316. continue
  317. }
  318. if member.Nick != "" {
  319. name = member.Nick
  320. } else {
  321. name = member.User.DisplayOrUsername()
  322. }
  323. } else {
  324. for _, recipient := range selectedChannel.DMRecipients {
  325. if recipient.ID == userID {
  326. name = recipient.DisplayOrUsername()
  327. break
  328. }
  329. }
  330. }
  331. if name != "" {
  332. names = append(names, name)
  333. }
  334. }
  335. switch len(names) {
  336. case 1:
  337. footer = names[0] + " is typing..."
  338. case 2:
  339. footer = fmt.Sprintf("%s and %s are typing...", names[0], names[1])
  340. case 3:
  341. footer = fmt.Sprintf("%s, %s, and %s are typing...", names[0], names[1], names[2])
  342. default:
  343. footer = "Several people are typing..."
  344. }
  345. }
  346. go m.app.QueueUpdateDraw(func() { m.messagesList.SetFooter(footer) })
  347. }