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