From 698a0adf93dd9a3e0e86910e45fdba02385bc1f8 Mon Sep 17 00:00:00 2001 From: Trevor Slocum Date: Wed, 20 May 2020 15:36:19 -0700 Subject: [PATCH] Add List.SetSelectedAlwaysCentered --- CHANGELOG | 3 +++ list.go | 38 +++++++++++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index d982885..db14ea6 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,6 @@ +v1.4.7 (WIP) +- Add List.SetSelectedAlwaysCentered + v1.4.6 (2020-05-18) - Add Box.ShowFocus - Add Keys to allow default keyboard shortcuts to be modified diff --git a/list.go b/list.go index 1274879..ae9319c 100644 --- a/list.go +++ b/list.go @@ -61,6 +61,9 @@ type List struct { // If true, the selection must remain visible when scrolling. selectedAlwaysVisible bool + // If true, the selection must remain centered when scrolling. + selectedAlwaysCentered bool + // If true, the entire row is highlighted when selected. highlightFullLine bool @@ -302,6 +305,16 @@ func (l *List) SetSelectedAlwaysVisible(alwaysVisible bool) *List { return l } +// SetSelectedAlwaysCentered sets a flag which determines whether the currently +// selected list item must remain centered when scrolling. +func (l *List) SetSelectedAlwaysCentered(alwaysCentered bool) *List { + l.Lock() + defer l.Unlock() + + l.selectedAlwaysCentered = alwaysCentered + return l +} + // SetHighlightFullLine sets a flag which determines whether the colored // background of selected items spans the entire width of the view. If set to // true, the highlight spans the entire view. If set to false, only the text of @@ -651,15 +664,30 @@ func (l *List) transform(tr Transformation) { func (l *List) updateOffset() { _, _, _, l.height = l.GetInnerRect() + h := l.height + if l.selectedAlwaysCentered { + h /= 2 + } + if l.currentItem < l.offset { l.offset = l.currentItem } else if l.showSecondaryText { - if 2*(l.currentItem-l.offset) >= l.height-1 { - l.offset = (2*l.currentItem + 3 - l.height) / 2 + if 2*(l.currentItem-l.offset) >= h-1 { + l.offset = (2*l.currentItem + 3 - h) / 2 } } else { - if l.currentItem-l.offset >= l.height { - l.offset = l.currentItem + 1 - l.height + if l.currentItem-l.offset >= h { + l.offset = l.currentItem + 1 - h + } + } + + if l.showSecondaryText { + if l.offset > len(l.items)-(l.height/2) { + l.offset = len(l.items) - l.height/2 + } + } else { + if l.offset > len(l.items)-l.height { + l.offset = len(l.items) - l.height } } } @@ -702,7 +730,7 @@ func (l *List) Draw(screen tcell.Screen) { } // Adjust offset to keep the current selection in view. - if l.selectedAlwaysVisible { + if l.selectedAlwaysVisible || l.selectedAlwaysCentered { l.updateOffset() }