summaryrefslogtreecommitdiff
path: root/animatedtext.go
blob: 155e371fdb374749a107c508bf4819b45b3f8391 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package animatedtext

import (
	"sync"
	"time"

	tea "github.com/charmbracelet/bubbletea"
)

var (
	lastID int
	mutex  sync.Mutex
)

func nextID() int {
	mutex.Lock()
	defer mutex.Unlock()
	lastID++
	return lastID
}

type AnimatedText struct {
	FullText       string
	PrintPauseTime time.Duration
}

type Model struct {
	AnimatedText AnimatedText

	id             int
	currentCharIdx int
	finished       bool
}

func New(text string, pauseTime time.Duration) Model {
	m := Model{
		AnimatedText:   AnimatedText{FullText: text, PrintPauseTime: pauseTime},
		id:             nextID(),
		currentCharIdx: 0,
	}

	return m
}

type TickMsg struct {
	Time time.Time
	ID   int
}

func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
	if m.finished {
		return m, nil
	}

	switch msg := msg.(type) {
	case TickMsg:
		if msg.ID > 0 && msg.ID != m.id {
			return m, nil
		}

		if m.currentCharIdx + 1 >= len(m.AnimatedText.FullText) {
			m.finished = true
			return m, nil
		}

		m.currentCharIdx++
		
		return m, m.tick(m.id)

	default:
		return m, nil
	}
}

func (m Model) View() string {
	if (m.finished) {
		return m.AnimatedText.FullText
	}

	return m.AnimatedText.FullText[0:m.currentCharIdx]
}

func (m Model) tick(id int) tea.Cmd {
	return tea.Tick(m.AnimatedText.PrintPauseTime, func(t time.Time) tea.Msg {
		return TickMsg{
			Time: t,
			ID:   id,
		}
	})
}

func Tick() tea.Msg {
	return TickMsg{Time: time.Now()}
}