-
-
Notifications
You must be signed in to change notification settings - Fork 270
/
model.go
316 lines (275 loc) · 7.02 KB
/
model.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package model
import (
"bufio"
_ "embed"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/atotto/clipboard"
"github.com/maaslalani/slides/internal/file"
"github.com/maaslalani/slides/internal/navigation"
"github.com/maaslalani/slides/internal/process"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/glamour"
"github.com/maaslalani/slides/internal/code"
"github.com/maaslalani/slides/internal/meta"
"github.com/maaslalani/slides/styles"
)
var (
//go:embed tutorial.md
slidesTutorial []byte
tabSpaces = strings.Repeat(" ", 4)
)
const (
delimiter = "\n---\n"
)
// Model represents the model of this presentation, which contains all the
// state related to the current slides.
type Model struct {
Slides []string
Page int
Author string
Date string
Theme glamour.TermRendererOption
Paging string
FileName string
viewport viewport.Model
buffer string
// VirtualText is used for additional information that is not part of the
// original slides, it will be displayed on a slide and reset on page change
VirtualText string
Search navigation.Search
}
type fileWatchMsg struct{}
var fileInfo os.FileInfo
// Init initializes the model and begins watching the slides file for changes
// if it exists.
func (m Model) Init() tea.Cmd {
if m.FileName == "" {
return nil
}
fileInfo, _ = os.Stat(m.FileName)
return fileWatchCmd()
}
func fileWatchCmd() tea.Cmd {
return tea.Every(time.Second, func(t time.Time) tea.Msg {
return fileWatchMsg{}
})
}
// Load loads all of the content and metadata for the presentation.
func (m *Model) Load() error {
var content string
var err error
if m.FileName != "" {
content, err = readFile(m.FileName)
} else {
content, err = readStdin()
}
if err != nil {
return err
}
content = strings.ReplaceAll(content, "\r", "")
content = strings.TrimPrefix(content, strings.TrimPrefix(delimiter, "\n"))
slides := strings.Split(content, delimiter)
metaData, exists := meta.New().Parse(slides[0])
// If the user specifies a custom configuration options
// skip the first "slide" since this is all configuration
if exists && len(slides) > 1 {
slides = slides[1:]
}
m.Slides = slides
m.Author = metaData.Author
m.Date = metaData.Date
m.Paging = metaData.Paging
if m.Theme == nil {
m.Theme = styles.SelectTheme(metaData.Theme)
}
return nil
}
// Update updates the presentation model.
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.viewport.Width = msg.Width
m.viewport.Height = msg.Height
return m, nil
case tea.KeyMsg:
keyPress := msg.String()
if m.Search.Active {
switch msg.Type {
case tea.KeyEnter:
// execute current buffer
if m.Search.Query() != "" {
m.Search.Execute(&m)
} else {
m.Search.Done()
}
// cancel search
return m, nil
case tea.KeyCtrlC, tea.KeyEscape:
// quit command mode
m.Search.SetQuery("")
m.Search.Done()
return m, nil
}
var cmd tea.Cmd
m.Search.SearchTextInput, cmd = m.Search.SearchTextInput.Update(msg)
return m, cmd
}
switch keyPress {
case "/":
// Begin search
m.Search.Begin()
m.Search.SearchTextInput.Focus()
return m, nil
case "ctrl+n":
// Go to next occurrence
m.Search.Execute(&m)
case "ctrl+e":
// Run code blocks
blocks, err := code.Parse(m.Slides[m.Page])
if err != nil {
// We couldn't parse the code block on the screen
m.VirtualText = "\n" + err.Error()
return m, nil
}
var outs []string
for _, block := range blocks {
res := code.Execute(block)
outs = append(outs, res.Out)
}
m.VirtualText = strings.Join(outs, "\n")
case "y":
blocks, err := code.Parse(m.Slides[m.Page])
if err != nil {
return m, nil
}
for _, b := range blocks {
_ = clipboard.WriteAll(b.Code)
}
return m, nil
case "ctrl+c", "q":
return m, tea.Quit
default:
newState := navigation.Navigate(navigation.State{
Buffer: m.buffer,
Page: m.Page,
TotalSlides: len(m.Slides),
}, keyPress)
m.buffer = newState.Buffer
m.SetPage(newState.Page)
}
case fileWatchMsg:
newFileInfo, err := os.Stat(m.FileName)
if err == nil && newFileInfo.ModTime() != fileInfo.ModTime() {
fileInfo = newFileInfo
_ = m.Load()
if m.Page >= len(m.Slides) {
m.Page = len(m.Slides) - 1
}
}
return m, fileWatchCmd()
}
return m, nil
}
// View renders the current slide in the presentation and the status bar which
// contains the author, date, and pagination information.
func (m Model) View() string {
r, _ := glamour.NewTermRenderer(m.Theme, glamour.WithWordWrap(m.viewport.Width))
slide := m.Slides[m.Page]
slide = code.HideComments(slide)
slide, err := r.Render(slide)
slide = strings.ReplaceAll(slide, "\t", tabSpaces)
slide += m.VirtualText
if err != nil {
slide = fmt.Sprintf("Error: Could not render markdown! (%v)", err)
}
slide = styles.Slide.Render(slide)
var left string
if m.Search.Active {
// render search bar
left = m.Search.SearchTextInput.View()
} else {
// render author and date
left = styles.Author.Render(m.Author) + styles.Date.Render(m.Date)
}
right := styles.Page.Render(m.paging())
status := styles.Status.Render(styles.JoinHorizontal(left, right, m.viewport.Width))
return styles.JoinVertical(slide, status, m.viewport.Height)
}
func (m *Model) paging() string {
switch strings.Count(m.Paging, "%d") {
case 2:
return fmt.Sprintf(m.Paging, m.Page+1, len(m.Slides))
case 1:
return fmt.Sprintf(m.Paging, m.Page+1)
default:
return m.Paging
}
}
func readFile(path string) (string, error) {
s, err := os.Stat(path)
if err != nil {
return "", errors.New("could not read file")
}
if s.IsDir() {
return "", errors.New("can not read directory")
}
b, err := os.ReadFile(path)
if err != nil {
return "", err
}
content := string(b)
// Pre-process slides if the file is executable to avoid
// unintentional code execution when presenting slides
if file.IsExecutable(s) {
// Remove shebang if file has one
if strings.HasPrefix(content, "#!") {
content = strings.Join(strings.SplitN(content, "\n", 2)[1:], "\n")
}
content = process.Pre(content)
}
return content, err
}
func readStdin() (string, error) {
stat, err := os.Stdin.Stat()
if err != nil {
return "", err
}
if stat.Mode()&os.ModeNamedPipe == 0 && stat.Size() == 0 {
return string(slidesTutorial), nil
}
reader := bufio.NewReader(os.Stdin)
var b strings.Builder
for {
r, _, err := reader.ReadRune()
if err != nil && err == io.EOF {
break
}
_, err = b.WriteRune(r)
if err != nil {
return "", err
}
}
return b.String(), nil
}
// CurrentPage returns the current page the presentation is on.
func (m *Model) CurrentPage() int {
return m.Page
}
// SetPage sets which page the presentation should render.
func (m *Model) SetPage(page int) {
if m.Page == page {
return
}
m.VirtualText = ""
m.Page = page
}
// Pages returns all the slides in the presentation.
func (m *Model) Pages() []string {
return m.Slides
}