model.go 9.9 KB

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