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 (v *Model) SelectedChannel() *discord.Channel {
  67. v.selectedChannelMu.RLock()
  68. defer v.selectedChannelMu.RUnlock()
  69. return v.selectedChannel
  70. }
  71. func (v *Model) SetSelectedChannel(channel *discord.Channel) {
  72. v.selectedChannelMu.Lock()
  73. v.selectedChannel = channel
  74. v.selectedChannelMu.Unlock()
  75. }
  76. func (v *Model) buildLayout() {
  77. v.Clear()
  78. v.rightFlex.Clear()
  79. v.mainFlex.Clear()
  80. v.rightFlex.
  81. SetDirection(flex.DirectionRow).
  82. AddItem(v.messagesList, 0, 1, false).
  83. AddItem(v.messageInput, 3, 1, false)
  84. // The guilds tree is always focused first at start-up.
  85. v.mainFlex.
  86. AddItem(v.guildsTree, 0, 1, true).
  87. AddItem(v.rightFlex, 0, 4, false)
  88. v.AddLayer(v.mainFlex, layers.WithName(flexLayerName), layers.WithResize(true), layers.WithVisible(true))
  89. v.AddLayer(v.messageInput.mentionsList, layers.WithName(mentionsListLayerName), layers.WithResize(false), layers.WithVisible(false))
  90. }
  91. func (v *Model) togglePicker() {
  92. if v.HasLayer(channelsPickerLayerName) {
  93. v.closePicker()
  94. } else {
  95. v.openPicker()
  96. }
  97. }
  98. func (v *Model) openPicker() {
  99. v.AddLayer(
  100. ui.Centered(v.channelsPicker, v.cfg.Picker.Width, v.cfg.Picker.Height),
  101. layers.WithName(channelsPickerLayerName),
  102. layers.WithResize(true),
  103. layers.WithVisible(true),
  104. layers.WithOverlay(),
  105. ).SendToFront(channelsPickerLayerName)
  106. v.channelsPicker.update()
  107. }
  108. func (v *Model) closePicker() {
  109. v.RemoveLayer(channelsPickerLayerName)
  110. v.channelsPicker.Update()
  111. }
  112. func (v *Model) toggleGuildsTree() {
  113. // The guilds tree is visible if the number of items is two.
  114. if v.mainFlex.GetItemCount() == 2 {
  115. v.mainFlex.RemoveItem(v.guildsTree)
  116. if v.guildsTree.HasFocus() {
  117. v.app.SetFocus(v.mainFlex)
  118. }
  119. } else {
  120. v.buildLayout()
  121. v.app.SetFocus(v.guildsTree)
  122. }
  123. }
  124. func (v *Model) focusGuildsTree() bool {
  125. // The guilds tree is not hidden if the number of items is two.
  126. if v.mainFlex.GetItemCount() == 2 {
  127. v.app.SetFocus(v.guildsTree)
  128. return true
  129. }
  130. return false
  131. }
  132. func (v *Model) focusMessageInput() bool {
  133. if !v.messageInput.GetDisabled() {
  134. v.app.SetFocus(v.messageInput)
  135. return true
  136. }
  137. return false
  138. }
  139. func (v *Model) focusPrevious() {
  140. switch v.app.Focused() {
  141. case v.messagesList: // Handle both a.messagesList and a.flex as well as other edge cases (if there is).
  142. if v.focusGuildsTree() {
  143. return
  144. }
  145. fallthrough
  146. case v.guildsTree:
  147. if v.focusMessageInput() {
  148. return
  149. }
  150. fallthrough
  151. case v.messageInput:
  152. v.app.SetFocus(v.messagesList)
  153. }
  154. }
  155. func (v *Model) focusNext() {
  156. switch v.app.Focused() {
  157. case v.messagesList:
  158. if v.focusMessageInput() {
  159. return
  160. }
  161. fallthrough
  162. case v.messageInput: // Handle both a.messageInput and a.flex as well as other edge cases (if there is).
  163. if v.focusGuildsTree() {
  164. return
  165. }
  166. fallthrough
  167. case v.guildsTree:
  168. v.app.SetFocus(v.messagesList)
  169. }
  170. }
  171. func (v *Model) HandleEvent(event tcell.Event) tview.Command {
  172. switch event := event.(type) {
  173. case *tview.InitEvent:
  174. return func() tcell.Event {
  175. if err := v.OpenState(v.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. v.closeState(),
  184. tview.Quit(),
  185. )
  186. case *tview.ModalDoneEvent:
  187. if v.HasLayer(confirmModalLayerName) {
  188. v.RemoveLayer(confirmModalLayerName)
  189. if v.confirmModalPreviousFocus != nil {
  190. v.app.SetFocus(v.confirmModalPreviousFocus)
  191. }
  192. onDone := v.confirmModalDone
  193. v.confirmModalDone = nil
  194. v.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, v.cfg.Keybinds.FocusGuildsTree.Keybind):
  203. v.messageInput.removeMentionsList()
  204. v.focusGuildsTree()
  205. return nil
  206. case keybind.Matches(event, v.cfg.Keybinds.FocusMessagesList.Keybind):
  207. v.messageInput.removeMentionsList()
  208. v.app.SetFocus(v.messagesList)
  209. return nil
  210. case keybind.Matches(event, v.cfg.Keybinds.FocusMessageInput.Keybind):
  211. v.focusMessageInput()
  212. return nil
  213. case keybind.Matches(event, v.cfg.Keybinds.FocusPrevious.Keybind):
  214. v.focusPrevious()
  215. return nil
  216. case keybind.Matches(event, v.cfg.Keybinds.FocusNext.Keybind):
  217. v.focusNext()
  218. return nil
  219. case keybind.Matches(event, v.cfg.Keybinds.Logout.Keybind):
  220. return tview.Batch(v.closeState(), v.logout())
  221. case keybind.Matches(event, v.cfg.Keybinds.ToggleGuildsTree.Keybind):
  222. v.toggleGuildsTree()
  223. return nil
  224. case keybind.Matches(event, v.cfg.Keybinds.ToggleChannelsPicker.Keybind):
  225. v.togglePicker()
  226. return nil
  227. }
  228. case *closeLayerEvent:
  229. if v.HasLayer(event.name) {
  230. v.HideLayer(event.name)
  231. }
  232. return nil
  233. }
  234. return v.Layers.HandleEvent(event)
  235. }
  236. func (v *Model) showConfirmModal(prompt string, buttons []string, onDone func(label string)) {
  237. v.confirmModalPreviousFocus = v.app.Focused()
  238. v.confirmModalDone = onDone
  239. modal := tview.NewModal().
  240. SetText(prompt).
  241. AddButtons(buttons)
  242. v.
  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 (v *Model) onReadUpdate(event *read.UpdateEvent) {
  253. v.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 := v.guildsTree.findNodeByReference(event.GuildID); guildNode != nil {
  258. v.guildsTree.setNodeLineStyle(guildNode, v.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 := v.guildsTree.findNodeByReference(event.ChannelID); channelNode != nil {
  264. v.guildsTree.setNodeLineStyle(channelNode, v.guildsTree.getChannelNodeStyle(event.ChannelID))
  265. }
  266. })
  267. }
  268. func (v *Model) clearTypers() {
  269. v.typersMu.Lock()
  270. for _, timer := range v.typers {
  271. timer.Stop()
  272. }
  273. clear(v.typers)
  274. v.typersMu.Unlock()
  275. v.updateFooter()
  276. }
  277. func (v *Model) addTyper(userID discord.UserID) {
  278. v.typersMu.Lock()
  279. typer, ok := v.typers[userID]
  280. if ok {
  281. typer.Reset(typingDuration)
  282. } else {
  283. v.typers[userID] = time.AfterFunc(typingDuration, func() {
  284. v.removeTyper(userID)
  285. })
  286. }
  287. v.typersMu.Unlock()
  288. v.updateFooter()
  289. }
  290. func (v *Model) removeTyper(userID discord.UserID) {
  291. v.typersMu.Lock()
  292. if typer, ok := v.typers[userID]; ok {
  293. typer.Stop()
  294. delete(v.typers, userID)
  295. }
  296. v.typersMu.Unlock()
  297. v.updateFooter()
  298. }
  299. func (v *Model) updateFooter() {
  300. selectedChannel := v.SelectedChannel()
  301. if selectedChannel == nil {
  302. return
  303. }
  304. guildID := selectedChannel.GuildID
  305. v.typersMu.RLock()
  306. defer v.typersMu.RUnlock()
  307. var footer string
  308. if len(v.typers) > 0 {
  309. var names []string
  310. for userID := range v.typers {
  311. var name string
  312. if guildID.IsValid() {
  313. member, err := v.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 v.app.QueueUpdateDraw(func() { v.messagesList.SetFooter(footer) })
  347. }