Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Table: Make UpdateViewport() have constant runtime, not depending on … #284

Merged
merged 3 commits into from
Dec 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions table/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ type Model struct {
styles Styles

viewport viewport.Model
start int
end int
}

// Row represents one line in the table.
Expand Down Expand Up @@ -242,7 +244,17 @@ func (m Model) View() string {
// columns and rows.
func (m *Model) UpdateViewport() {
renderedRows := make([]string, 0, len(m.rows))
for i := range m.rows {

// Render only rows from: m.cursor-m.viewport.Height to: m.cursor+m.viewport.Height
// Constant runtime, independent of number of rows in a table.
// Limits the numer of renderedRows to a maximum of 2*m.viewport.Height
if m.cursor >= 0 {
m.start = clamp(m.cursor-m.viewport.Height, 0, m.cursor)
} else {
m.start = 0
}
m.end = clamp(m.cursor+m.viewport.Height, m.cursor, len(m.rows))
for i := m.start; i < m.end; i++ {
renderedRows = append(renderedRows, m.renderRow(i))
}

Expand Down Expand Up @@ -300,11 +312,16 @@ func (m *Model) SetCursor(n int) {
// It can not go above the first row.
func (m *Model) MoveUp(n int) {
m.cursor = clamp(m.cursor-n, 0, len(m.rows)-1)
switch {
case m.start == 0:
m.viewport.SetYOffset(clamp(m.viewport.YOffset, 0, m.cursor))
case m.start < m.viewport.Height:
m.viewport.SetYOffset(clamp(m.viewport.YOffset+n, 0, m.cursor))
case m.viewport.YOffset >= 1:
m.viewport.YOffset = clamp(m.viewport.YOffset+n, 1, m.viewport.Height)
}
m.UpdateViewport()

if m.cursor < m.viewport.YOffset {
m.viewport.SetYOffset(m.cursor)
}
}

// MoveDown moves the selection down by any number of row.
Expand All @@ -313,8 +330,14 @@ func (m *Model) MoveDown(n int) {
m.cursor = clamp(m.cursor+n, 0, len(m.rows)-1)
m.UpdateViewport()

if m.cursor > (m.viewport.YOffset + (m.viewport.Height - 1)) {
m.viewport.SetYOffset(m.cursor - (m.viewport.Height - 1))
switch {
case m.end == len(m.rows):
m.viewport.SetYOffset(clamp(m.viewport.YOffset-n, 1, m.viewport.Height))
case m.cursor > (m.end-m.start)/2:
m.viewport.SetYOffset(clamp(m.viewport.YOffset-n, 1, m.cursor))
case m.viewport.YOffset > 1:
case m.cursor > m.viewport.YOffset+m.viewport.Height-1:
m.viewport.SetYOffset(clamp(m.viewport.YOffset+1, 0, 1))
}
}

Expand Down