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

fix(console): avoid crash when accessing selected item #570

Merged
merged 2 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
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
6 changes: 3 additions & 3 deletions tokio-console/src/view/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl View {
// mutate the currently selected view.
match event {
key!(Enter) => {
if let Some(task) = self.tasks_list.selected_item().upgrade() {
if let Some(task) = self.tasks_list.selected_item() {
update_kind = UpdateKind::SelectTask(task.borrow().span_id());
self.state = TaskInstance(self::task::TaskView::new(
task,
Expand All @@ -149,7 +149,7 @@ impl View {
ResourcesList => {
match event {
key!(Enter) => {
if let Some(res) = self.resources_list.selected_item().upgrade() {
if let Some(res) = self.resources_list.selected_item() {
update_kind = UpdateKind::SelectResource(res.borrow().span_id());
self.state = ResourceInstance(self::resource::ResourceView::new(res));
}
Expand All @@ -169,7 +169,7 @@ impl View {
update_kind = UpdateKind::Other;
}
key!(Enter) => {
if let Some(op) = view.async_ops_table.selected_item().upgrade() {
if let Some(op) = view.async_ops_table.selected_item() {
if let Some(task_id) = op.borrow().task_id() {
let task = self
.tasks_list
Expand Down
22 changes: 13 additions & 9 deletions tokio-console/src/view/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use ratatui::{
use std::convert::TryFrom;

use std::cell::RefCell;
use std::rc::Weak;
use std::rc::{Rc, Weak};

pub(crate) trait TableList<const N: usize> {
type Row;
Expand Down Expand Up @@ -154,18 +154,22 @@ impl<T: TableList<N>, const N: usize> TableListState<T, N> {
self.scroll_with(|_, _| 0)
}

pub(in crate::view) fn selected_item(&self) -> Weak<RefCell<T::Row>> {
pub(in crate::view) fn selected_item(&self) -> Option<Rc<RefCell<T::Row>>> {
self.table_state
.selected()
.map(|i| {
let selected = if self.sort_descending {
i
.and_then(|i| {
if self.sort_descending {
if i < self.sorted_items.len() {
Some(self.sorted_items[i].clone())
} else {
None
}
} else {
self.sorted_items.len() - i - 1
};
self.sorted_items[selected].clone()
let adjusted_index = self.sorted_items.len().checked_sub(i + 1)?;
self.sorted_items.get(adjusted_index).cloned()
}
})
.unwrap_or_default()
.and_then(|weak| weak.upgrade())
}

pub(in crate::view) fn render(
Expand Down
Loading