Fix slice out of bounds errors that could happen when deleting text

This commit is contained in:
Christian Rocha 2020-07-21 18:22:18 -04:00
parent 5357dd61bd
commit 10022c964c
No known key found for this signature in database
GPG Key ID: D6CC7A16E5878018

View File

@ -282,8 +282,10 @@ func Update(msg tea.Msg, m Model) (Model, tea.Cmd) {
fallthrough fallthrough
case tea.KeyDelete: case tea.KeyDelete:
if len(m.value) > 0 { if len(m.value) > 0 {
m.value = append(m.value[:m.pos-1], m.value[m.pos:]...) m.value = append(m.value[:max(0, m.pos-1)], m.value[m.pos:]...)
m.pos-- if m.pos > 0 {
m.pos--
}
} }
case tea.KeyLeft: case tea.KeyLeft:
if msg.Alt { // alt+left arrow, back one word if msg.Alt { // alt+left arrow, back one word
@ -366,7 +368,7 @@ func View(model tea.Model) string {
} }
value := m.value[m.offset:m.offsetRight] value := m.value[m.offset:m.offsetRight]
pos := m.pos - m.offset pos := max(0, m.pos-m.offset)
v := m.colorText(string(value[:pos])) v := m.colorText(string(value[:pos]))