Skip to content

Commit

Permalink
Moves history position managment inside history object
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Oct 24, 2023
1 parent 47c9736 commit 6832909
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
13 changes: 3 additions & 10 deletions pkg/cli/editor.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ func NewEditor(history *History) *Editor {
}

func (ed *Editor) EditRequest(keyStream <-chan keyboard.KeyEvent, initBuffer string) (string, error) {
historyIndex := 0

ed.History.ResetPosition()
fmt.Print(ed.content.ReplaceText(initBuffer))

for e := range keyStream {
Expand Down Expand Up @@ -61,25 +60,19 @@ func (ed *Editor) EditRequest(keyStream <-chan keyboard.KeyEvent, initBuffer str
case keyboard.KeyArrowRight:
fmt.Print(ed.content.MovePositionRight())
case keyboard.KeyArrowUp:
historyIndex++
req := ed.History.GetRequst(historyIndex)
req := ed.History.PrevRequst()

if req == "" {
fmt.Print(Bell)
historyIndex--

continue
}

fmt.Print(ed.content.ReplaceText(req))
case keyboard.KeyArrowDown:
historyIndex--
req := ed.History.GetRequst(historyIndex)
req := ed.History.NextRequst()

if req == "" {
fmt.Print(Bell)
historyIndex++

continue
}

Expand Down
31 changes: 27 additions & 4 deletions pkg/cli/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ type History struct {
fileName string
requests []string
limit uint
pos int
}

func NewHistory(fileName string, limit uint) *History {
h := &History{
fileName: fileName,
limit: limit,
requests: make([]string, 0),
pos: 0,
}

_ = h.loadFromFile()
Expand Down Expand Up @@ -57,6 +59,8 @@ func (h *History) loadFromFile() error {
h.requests = append(h.requests, line)
}

h.pos = len(h.requests) - 1

return nil
}

Expand Down Expand Up @@ -106,16 +110,35 @@ func (h *History) AddRequest(request string) {
}

h.requests = append(h.requests, request)
h.pos = len(h.requests) - 1
}

func (h *History) GetRequst(pos int) string {
if pos <= 0 {
func (h *History) PrevRequst() string {
if h.pos <= 0 {
return ""
}

if pos > len(h.requests) {
req := h.requests[h.pos]
h.pos--

return req
}

func (h *History) NextRequst() string {
if h.pos >= len(h.requests)-1 {
return ""
}

return h.requests[len(h.requests)-pos]
h.pos++
req := h.requests[h.pos]

return req
}

func (h *History) ResetPosition() {
if len(h.requests) == 0 {
return
}

h.pos = len(h.requests) - 1
}

0 comments on commit 6832909

Please sign in to comment.