image.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Based on the implementation by @trashhalo at:
  2. // https://github.com/trashhalo/imgcat
  3. package image
  4. import (
  5. "fmt"
  6. _ "image/jpeg"
  7. _ "image/png"
  8. tea "github.com/charmbracelet/bubbletea/v2"
  9. )
  10. type Model struct {
  11. url string
  12. image string
  13. width uint
  14. height uint
  15. err error
  16. }
  17. func New(width, height uint, url string) Model {
  18. return Model{
  19. width: width,
  20. height: height,
  21. url: url,
  22. }
  23. }
  24. func (m Model) Init() tea.Cmd {
  25. return nil
  26. }
  27. func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
  28. switch msg := msg.(type) {
  29. case errMsg:
  30. m.err = msg
  31. return m, nil
  32. case redrawMsg:
  33. m.width = msg.width
  34. m.height = msg.height
  35. m.url = msg.url
  36. return m, loadURL(m.url)
  37. case loadMsg:
  38. return handleLoadMsg(m, msg)
  39. }
  40. return m, nil
  41. }
  42. func (m Model) View() string {
  43. if m.err != nil {
  44. return fmt.Sprintf("couldn't load image(s): %v", m.err)
  45. }
  46. return m.image
  47. }
  48. type errMsg struct{ error }
  49. func (m Model) Redraw(width uint, height uint, url string) tea.Cmd {
  50. return func() tea.Msg {
  51. return redrawMsg{
  52. width: width,
  53. height: height,
  54. url: url,
  55. }
  56. }
  57. }
  58. func (m Model) UpdateURL(url string) tea.Cmd {
  59. return func() tea.Msg {
  60. return redrawMsg{
  61. width: m.width,
  62. height: m.height,
  63. url: url,
  64. }
  65. }
  66. }
  67. type redrawMsg struct {
  68. width uint
  69. height uint
  70. url string
  71. }
  72. func (m Model) IsLoading() bool {
  73. return m.image == ""
  74. }