forked from metafates/mangal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmini.go
120 lines (97 loc) · 2.21 KB
/
mini.go
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package mini
import (
"errors"
"github.com/metafates/mangal/source"
"github.com/metafates/mangal/util"
"github.com/samber/lo"
"os"
)
var (
truncateAt = 100
)
type Options struct {
Download bool
Continue bool
}
type mini struct {
width, height int
state state
statesHistory util.Stack[state]
download bool
selectedSource source.Source
cachedMangas map[string][]*source.Manga
cachedChapters map[string][]*source.Chapter
cachedPages map[string][]*source.Page
query string
selectedManga *source.Manga
selectedChapters []*source.Chapter
}
func newMini() *mini {
return &mini{
statesHistory: util.Stack[state]{},
cachedMangas: make(map[string][]*source.Manga),
cachedChapters: make(map[string][]*source.Chapter),
cachedPages: make(map[string][]*source.Page),
}
}
func (m *mini) previousState() {
if m.statesHistory.Len() > 0 {
m.setState(m.statesHistory.Pop())
}
}
func (m *mini) setState(s state) {
m.state = s
}
func (m *mini) newState(s state) {
// do not push state if it is the same as the current state
if m.state == s {
return
}
// Transitioning to these states is not allowed (it makes no sense)
if !lo.Contains([]state{}, m.state) {
m.statesHistory.Push(m.state)
}
m.setState(s)
}
func Run(options *Options) error {
if options.Continue && options.Download {
return errors.New("cannot download and continue")
}
m := newMini()
m.state = sourceSelectState
if options.Continue {
m.state = historySelectState
}
m.download = options.Download
if w, h, err := util.TerminalSize(); err == nil {
m.width, m.height = w, h
truncateAt = w
}
var err error
for {
if m.handleState() != nil {
return err
}
}
}
func (m *mini) handleState() error {
switch m.state {
case historySelectState:
return m.handleHistorySelectState()
case sourceSelectState:
return m.handleSourceSelectState()
case mangasSearchState:
return m.handleMangaSearchState()
case mangaSelectState:
return m.handleMangaSelectState()
case chapterSelectState:
return m.handleChapterSelectState()
case chapterReadState:
return m.handleChapterReadState()
case chaptersDownloadState:
return m.handleChaptersDownloadState()
case quitState:
os.Exit(0)
}
return nil
}