model.go 10 KB

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