Skip to content

Commit

Permalink
feat(console): Add vi style keybinds for tables
Browse files Browse the repository at this point in the history
Adds `hjkl` as alternatives to the arrow keys and `G` and `gg` to navigate
to the first and last rows in tables, respectively.
  • Loading branch information
k0nserv committed Dec 17, 2021
1 parent 28a4321 commit a206da6
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions console/src/view/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ pub(crate) struct TableListState<T: TableList> {
pub(crate) selected_column: usize,
pub(crate) sort_descending: bool,
pub(crate) table_state: TableState,

last_key_event: Option<input::KeyEvent>,
}

impl<T: TableList> TableListState<T> {
Expand All @@ -61,33 +63,40 @@ impl<T: TableList> TableListState<T> {
}
}

pub(in crate::view) fn key_input(&mut self, input::KeyEvent { code, .. }: input::KeyEvent) {
pub(in crate::view) fn key_input(&mut self, event: input::KeyEvent) {
use input::KeyCode::*;
let header_len = T::HEADER.len();
let code = event.code;
match code {
Left => {
Left | Char('h') => {
if self.selected_column == 0 {
self.selected_column = header_len - 1;
} else {
self.selected_column -= 1;
}
}
Right => {
Right | Char('l') => {
if self.selected_column == header_len - 1 {
self.selected_column = 0;
} else {
self.selected_column += 1;
}
}
Char('i') => self.sort_descending = !self.sort_descending,
Down => self.scroll_next(),
Up => self.scroll_prev(),
Down | Char('j') => self.scroll_next(),
Up | Char('k') => self.scroll_prev(),
Char('G') => self.scroll_to_last(),
Char('g') if self.last_key_event.map(|e| e.code) == Some(Char('g')) => {
self.scroll_to_first()
}
_ => {} // do nothing for now...
}

if let Ok(sort_by) = T::Sort::try_from(self.selected_column) {
self.sort_by = sort_by;
}

self.last_key_event = Some(event);
}

pub(in crate::view) fn scroll_with(
Expand Down Expand Up @@ -133,6 +142,14 @@ impl<T: TableList> TableListState<T> {
})
}

pub(in crate::view) fn scroll_to_last(&mut self) {
self.scroll_with(|resources, _| resources.len() - 1)
}

pub(in crate::view) fn scroll_to_first(&mut self) {
self.scroll_with(|_, _| 0)
}

pub(in crate::view) fn selected_item(&self) -> Weak<RefCell<T::Row>> {
self.table_state
.selected()
Expand Down Expand Up @@ -189,6 +206,7 @@ where
table_state: Default::default(),
selected_column,
sort_descending: false,
last_key_event: None,
}
}
}

0 comments on commit a206da6

Please sign in to comment.