Repository navigation
Expand file tree
/
Copy pathtestcheck.go
More file actions
276 lines (240 loc) · 8.29 KB
/
Copy pathtestcheck.go
File metadata and controls
276 lines (240 loc) · 8.29 KB
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
package main
import (
"errors"
"fmt"
"math/rand"
"os"
"slices"
"strings"
"unicode/utf8"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textarea"
"github.com/charmbracelet/bubbles/viewport"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/term"
)
type Question struct {
Answer string
Text string
}
func (q *Question) PrintAnswer(consoleWidth int) string {
return printWithoutBreaksInWords(q.Answer, consoleWidth)
}
func (q *Question) PrintText(consoleWidth int) string {
return printWithoutBreaksInWords(q.Text, consoleWidth)
}
// printWithoutBreaksInWords wraps each line on its own, so the line breaks a
// code snippet was written with survive into the panel.
func printWithoutBreaksInWords(text string, consoleWidth int) (splitText string) {
lines := []string{}
for line := range strings.SplitSeq(text, "\n") {
lines = append(lines, wrapWithoutBreaksInWords(line, consoleWidth))
}
return strings.Join(lines, "\n")
}
func wrapWithoutBreaksInWords(text string, consoleWidth int) (splitText string) {
var builder strings.Builder
var counter int
var index int
var lastWhitespaceIdx int
runes := []rune(text)
for counter < len(runes) {
if index == consoleWidth {
originalCounter := counter
counter = lastWhitespaceIdx
if counter == 0 || index == 0 {
counter = originalCounter - 1
}
index = 0
builder.WriteRune('\n')
}
if runes[counter] == ' ' || counter == len(runes)-1 {
if counter == len(runes)-1 {
counter++
}
switch {
case lastWhitespaceIdx == 0:
if counter + 1 >= len(runes) {
builder.WriteString(string(runes[0 : counter]))
} else {
builder.WriteString(string(runes[0 : counter+1]))
}
case lastWhitespaceIdx+1 < counter && counter != len(runes):
builder.WriteString(string(runes[lastWhitespaceIdx+1 : counter+1]))
case lastWhitespaceIdx+1 < counter:
builder.WriteString(string(runes[lastWhitespaceIdx+1 : counter]))
}
lastWhitespaceIdx = counter
}
index++
counter++
}
splitText = builder.String()
return
}
type TestCheck struct {
viewport viewport.Model
textarea textarea.Model
vpFailed viewport.Model
// failedPanel is what vpFailed has been given to show. A viewport hands
// back its rendered view, borders and all, and never its content, so the
// content has to be kept here to be able to add to it.
failedPanel string
Questions []Question
SuccessQuestions []Question
FailedQuestions []Question
CurrentQuestion *Question
LastQuestionSuccess bool
}
// panelBorderColumns is what the two panels spend on their own borders: a
// left and a right column each. The panels have to be laid out inside what
// is left, or the pair of them comes out wider than the terminal.
const panelBorderColumns = 4
const (
initialTextareaHeight = 2
smallAnswerLen = 10
mediumAnswerLen = 15
bigAnswerLen = 25
paragraphAnswerLen = 100
poemAnswerLength = 250
dissertationAnswerLength = 1000
)
func (m *TestCheck) setContentWhenNoMoreQuestions() {
sb := strings.Builder{}
if len(m.FailedQuestions) > 0 {
fmt.Fprintf(&sb, "Неправильно ответил на %d вопросов из %d.\n",
len(m.FailedQuestions),
len(m.FailedQuestions)+len(m.SuccessQuestions))
sb.WriteString("Заваленные вопросы:\n")
for _, question := range m.FailedQuestions {
fmt.Fprintf(&sb, "Вопрос: %s\nОтвет: %s\n", question.Text, question.Answer)
}
} else {
sb.WriteString("Вы не завалили ни одного вопроса. Молодец!\n")
}
resultString := sb.String()
m.viewport.SetContent(resultString)
m.viewport.Height = strings.Count(resultString, "\n") + 3
m.viewport.Style.Padding(1)
}
func (m *TestCheck) computeDistanceBetweenInputAndAnswer() (distance int) {
distance = Ld(IgnoreIndentation(m.textarea.Value()), IgnoreIndentation(m.CurrentQuestion.Answer))
return
}
func (m *TestCheck) IsInputAndAnswerEqual(distance int) (result bool) {
answerLen := utf8.RuneCountInString(IgnoreIndentation(m.CurrentQuestion.Answer))
if answerLen <= smallAnswerLen {
result = distance <= 0
} else if answerLen <= mediumAnswerLen {
result = distance <= 2
} else if answerLen <= bigAnswerLen {
result = distance <= 4
} else if answerLen <= paragraphAnswerLen {
result = distance <= 8
} else if answerLen <= poemAnswerLength {
result = distance <= 16
} else if answerLen <= dissertationAnswerLength {
result = distance <= 32
} else {
result = distance < 100
}
return
}
func initializeModel(questions []Question) (testCheckModel TestCheck, err error) {
width, height, termSizeErr := term.GetSize(os.Stdout.Fd())
if termSizeErr != nil {
panic(termSizeErr)
}
panelsWidth := width - panelBorderColumns
rightPanelWidth := panelsWidth * 3 / 7
leftPanelWidth := panelsWidth - rightPanelWidth
if len(questions) == 0 {
err = errors.New("выбранный файл не содержит вопросов попробуйте добавить новые")
return TestCheck{}, err
}
currentQuestion := questions[rand.Intn(len(questions))]
taModel := textarea.New()
taModel.Focus()
taModel.SetHeight(initialTextareaHeight)
taModel.KeyMap = textarea.DefaultKeyMap
// Enter submits the answer, so a line break needs a key of its own.
taModel.KeyMap.InsertNewline = key.NewBinding(
key.WithKeys(newLineKeys...),
key.WithHelp("shift+enter", "новая строка"))
taModel.Placeholder = defaultTaPlaceholder
taModel.FocusedStyle.CursorLine = lipgloss.NewStyle()
taModel.ShowLineNumbers = false
taModel.SetWidth(leftPanelWidth)
taModel.FocusedStyle.Base = lipgloss.NewStyle().Border(lipgloss.MarkdownBorder(), false, false, false, true)
vpModel := viewport.New(leftPanelWidth, 8)
vpModel.KeyMap = viewport.KeyMap{}
vpModel.KeyMap.Down = key.NewBinding(key.WithKeys("down"))
vpModel.KeyMap.Up = key.NewBinding(key.WithKeys("up"))
vpModel.Style = vpModel.Style.Border(
lipgloss.DoubleBorder(),
true, true,
).
BorderForeground(lipgloss.Color("6")).
Foreground(lipgloss.Color("180"))
vpModel.SetContent(currentQuestion.PrintText(vpModel.Width))
vpFailedModel := viewport.New(rightPanelWidth, height-2)
vpFailedModel.KeyMap = viewport.KeyMap{}
vpFailedModel.KeyMap.Down = key.NewBinding(key.WithKeys("down"))
vpFailedModel.KeyMap.Up = key.NewBinding(key.WithKeys("up"))
vpFailedModel.Style = vpFailedModel.Style.Border(
lipgloss.NormalBorder(),
true,
).
BorderForeground(lipgloss.Color("52"))
testCheckModel = TestCheck{
viewport: vpModel,
textarea: taModel,
vpFailed: vpFailedModel,
Questions: questions,
SuccessQuestions: []Question{},
FailedQuestions: []Question{},
CurrentQuestion: ¤tQuestion,
LastQuestionSuccess: true,
}
return
}
// growTextareaToFitInput keeps every line the answer has so far on screen,
// whether the lines came from wrapping or from shift+enter.
func (m *TestCheck) growTextareaToFitInput() {
needed := max(m.textarea.Height(), m.textarea.LineCount())
if m.textarea.Length() >= m.textarea.Width()*m.textarea.Height() {
needed++
}
if needed == m.textarea.Height() {
return
}
currentContent := m.textarea.Value()
m.textarea.SetHeight(needed)
m.textarea.SetValue(currentContent)
}
func (m *TestCheck) prepareNextQuestion() {
m.textarea.SetHeight(initialTextareaHeight)
questionIndex := slices.Index(m.Questions, *m.CurrentQuestion)
m.Questions = slices.Delete(m.Questions, questionIndex, questionIndex+1)
questionsToAskCount := len(m.Questions)
if questionsToAskCount > 0 {
selectedQuestionIndex := rand.Intn(questionsToAskCount)
m.CurrentQuestion = &m.Questions[selectedQuestionIndex]
resultString := m.CurrentQuestion.PrintText(m.viewport.Width)
m.viewport.SetContent(resultString)
m.viewport.Height = strings.Count(resultString, "\n") + 3
} else {
m.setContentWhenNoMoreQuestions()
}
}
// prepareFailedVpContent puts the pair just failed at the top of the panel,
// above the ones failed before it.
func (m *TestCheck) prepareFailedVpContent(yourAnswer string) {
latest := printWithoutBreaksInWords("V: "+m.CurrentQuestion.Answer, m.vpFailed.Width-1) + "\n" +
printWithoutBreaksInWords("X: "+yourAnswer, m.vpFailed.Width-1) + "\n"
if m.failedPanel != "" {
latest += "\n"
}
m.failedPanel = latest + m.failedPanel
m.vpFailed.SetContent(m.failedPanel)
}