model.go 9.9 KB

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