feat(tui): improve tab navigation

This commit is contained in:
objz committed 2025-10-18 16:15:09 +02:00
1 parent 6c92c6132a
commit 09d548272b
7 files changed
+224 -94

No files matched your search

+26 -15
View File
@@ -29,6 +29,7 @@ pub struct App {
exit: bool,
focused: FocusedArea,
pre_overlay_focused: FocusedArea,
content_tab: widgets::content::ContentTab,
profiles_state: profiles::State,
instance_manager: InstanceManager,
log_list_state: tui_logger::TuiWidgetState,
@@ -83,6 +84,7 @@ impl Default for App {
exit: false,
focused: FocusedArea::default(),
pre_overlay_focused: FocusedArea::default(),
content_tab: widgets::content::ContentTab::default(),
profiles_state,
instance_manager: manager,
log_list_state: tui_logger::TuiWidgetState::new()
@@ -131,8 +133,13 @@ impl App {
])
.split(chunks[1]);
widgets::content::title(frame, main_chunks[0], self.focused);
widgets::content::render(frame, main_chunks[1], self.focused);
widgets::content::title(
frame,
main_chunks[0],
self.focused,
self.profiles_state.selected_instance(),
);
widgets::content::render(frame, main_chunks[1], self.focused, self.content_tab);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
@@ -270,6 +277,12 @@ impl App {
self.pre_overlay_focused = self.focused;
self.focused = FocusedArea::StatusExpanded;
}
KeyCode::Tab if self.focused == FocusedArea::Content => {
self.content_tab = self.content_tab.next();
}
KeyCode::BackTab if self.focused == FocusedArea::Content => {
self.content_tab = self.content_tab.previous();
}
KeyCode::Char('d')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
@@ -359,7 +372,7 @@ impl App {
fn render_log_overlay(frame: &mut Frame, log_state: &mut tui_logger::TuiWidgetState) {
use crate::tui::theme::THEME;
use ratatui::{
layout::{Alignment, Rect},
layout::{Alignment, Margin},
style::{Modifier, Style},
text::Line,
widgets::{Block, BorderType, Clear},
@@ -367,12 +380,7 @@ impl App {
use tui_logger::TuiLoggerWidget;
let area = frame.area();
let overlay = Rect {
x: area.x + 1,
y: area.y + 1,
width: area.width.saturating_sub(2),
height: area.height.saturating_sub(2),
};
let overlay = area.inner(Margin::new(1, 1));
frame.render_widget(Clear, overlay);
@@ -426,15 +434,18 @@ impl App {
elapsed_ms: u128,
) {
use crate::tui::theme::THEME;
const FADE_OUT_MS: u128 = 500;
let fade_start_ms = error_buffer::AUTO_DISMISS_MS.saturating_sub(FADE_OUT_MS);
const FLY_OUT_MS: u128 = 300;
let fly_start_ms = error_buffer::AUTO_DISMISS_MS.saturating_sub(FLY_OUT_MS);
if elapsed_ms >= fade_start_ms {
if elapsed_ms >= fly_start_ms {
let entry = self.error_effects.entry(event.id).or_insert(ErrorEffectState::Idle);
if !matches!(entry, ErrorEffectState::FadingOut(_)) {
*entry = ErrorEffectState::FadingOut(tachyonfx::fx::fade_to_fg(
THEME.colors.fade_to,
(FADE_OUT_MS as u32, Interpolation::SineIn),
*entry = ErrorEffectState::FadingOut(fx::slide_out(
Motion::LeftToRight,
8,
0,
THEME.colors.popup_bg,
(FLY_OUT_MS as u32, Interpolation::SineIn),
));
}
}
+3 -37
View File
@@ -5,45 +5,11 @@ pub mod progress;
pub mod theme;
pub mod widgets;
use std::io::{stdout, Result, Stdout};
use crossterm::{
execute,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{prelude::CrosstermBackend, Terminal};
pub type Tui = ratatui::DefaultTerminal;
pub async fn show() -> color_eyre::Result<()> {
let mut terminal = init_ratatui()?;
let mut terminal = ratatui::init();
let result = layout::App::default().run(&mut terminal).await;
if let Err(err) = restore_ratatui() {
eprintln!(
"failed to restore terminal. Run 'reset' or restart your terminal to recover: {}",
err
);
}
ratatui::restore();
result
}
pub type Tui = Terminal<CrosstermBackend<Stdout>>;
fn init_ratatui() -> Result<Tui> {
execute!(stdout(), EnterAlternateScreen)?;
enable_raw_mode()?;
set_panic_hook();
Terminal::new(CrosstermBackend::new(stdout()))
}
fn set_panic_hook() {
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |panic_info| {
let _ = restore_ratatui();
hook(panic_info);
}));
}
fn restore_ratatui() -> Result<()> {
execute!(stdout(), LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
}
+144 -23
View File
@@ -1,7 +1,8 @@
use ratatui::{
layout::Rect,
style::Style,
widgets::{Block, BorderType, Borders, Paragraph},
layout::{Alignment, Constraint, Layout, Rect},
style::{Modifier, Style},
text::Span,
widgets::{Block, BorderType, Borders, Paragraph, Tabs},
Frame,
};
@@ -10,7 +11,110 @@ use crate::tui::theme::THEME;
use super::styled_title;
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea) {
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ContentTab {
#[default]
Mods,
ResourcePacks,
Shaders,
Screenshots,
Worlds,
Logs,
}
impl ContentTab {
const ALL: &'static [ContentTab] = &[
ContentTab::Mods,
ContentTab::ResourcePacks,
ContentTab::Shaders,
ContentTab::Screenshots,
ContentTab::Worlds,
ContentTab::Logs,
];
pub fn label(self) -> &'static str {
match self {
ContentTab::Mods => "Mods",
ContentTab::ResourcePacks => "Resource Packs",
ContentTab::Shaders => "Shaders",
ContentTab::Screenshots => "Screenshots",
ContentTab::Worlds => "Worlds",
ContentTab::Logs => "Logs",
}
}
pub fn index(self) -> usize {
Self::ALL.iter().position(|&t| t == self).unwrap_or(0)
}
pub fn next(self) -> Self {
Self::ALL[(self.index() + 1) % Self::ALL.len()]
}
pub fn previous(self) -> Self {
let idx = self.index();
Self::ALL[if idx == 0 {
Self::ALL.len() - 1
} else {
idx - 1
}]
}
}
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, tab: ContentTab) {
let border_color = if focused == FocusedArea::Content {
THEME.colors.border_focused
} else {
THEME.colors.border_unfocused
};
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(border_color));
let inner = block.inner(area);
frame.render_widget(block, area);
let [tabs_area, content_area] =
Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(inner);
let tab_titles: Vec<&str> = ContentTab::ALL.iter().map(|t| t.label()).collect();
let tabs = Tabs::new(tab_titles)
.select(tab.index())
.highlight_style(
Style::default()
.fg(THEME.colors.accent)
.add_modifier(Modifier::BOLD),
)
.divider(Span::styled(
" │ ",
Style::default().fg(THEME.colors.border_unfocused),
));
frame.render_widget(tabs, tabs_area);
let body = match tab {
ContentTab::Mods => "No mods installed.",
ContentTab::ResourcePacks => "No resource packs installed.",
ContentTab::Shaders => "No shaders installed.",
ContentTab::Screenshots => "No screenshots.",
ContentTab::Worlds => "No worlds saved.",
ContentTab::Logs => "No logs yet.",
};
frame.render_widget(
Paragraph::new(body).style(Style::default().fg(THEME.colors.text_idle)),
content_area,
);
}
pub fn title(
frame: &mut Frame,
area: Rect,
focused: FocusedArea,
instance: Option<&crate::instance::InstanceConfig>,
) {
let color = if focused == FocusedArea::Content {
THEME.colors.border_focused
} else {
@@ -23,23 +127,40 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea) {
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(color));
let widget = Paragraph::new("TEST CONTENT").block(block);
frame.render_widget(widget, area);
}
pub fn title(frame: &mut Frame, area: Rect, focused: FocusedArea) {
let color = if focused == FocusedArea::Content {
THEME.colors.border_focused
} else {
THEME.colors.border_unfocused
};
let block = Block::default()
.title(styled_title("Title", false))
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(color));
let widget = Paragraph::new("TEST CONTENT").block(block);
frame.render_widget(widget, area);
let inner = block.inner(area);
frame.render_widget(block, area);
match instance {
None => {
frame.render_widget(
Paragraph::new("No instance selected")
.style(Style::default().fg(THEME.colors.text_idle)),
inner,
);
}
Some(inst) => {
let [left_area, right_area] =
Layout::horizontal([Constraint::Min(0), Constraint::Length(32)]).areas(inner);
frame.render_widget(
Paragraph::new(inst.name.as_str()).style(
Style::default()
.fg(THEME.colors.foreground)
.add_modifier(Modifier::BOLD),
),
left_area,
);
let loader_str = match &inst.loader_version {
Some(lv) => format!("{} \u{00b7} {} {}", inst.game_version, inst.loader, lv),
None => format!("{} \u{00b7} {}", inst.game_version, inst.loader),
};
frame.render_widget(
Paragraph::new(loader_str)
.style(Style::default().fg(THEME.colors.border_focused))
.alignment(Alignment::Right),
right_area,
);
}
}
}
+5 -2
View File
@@ -89,12 +89,15 @@ impl Widget for ConfirmPopup {
}
pub fn confirm_popup_area(frame_area: Rect, name: &str) -> Rect {
use super::{centered_rect, word_wrap_size};
use super::word_wrap_size;
use ratatui::layout::Constraint;
const MAX_W: usize = 48;
const BODY: &str = "This will permanently remove the instance";
let title_w = name.len() + 12;
let (body_w, _) = word_wrap_size(BODY, MAX_W);
let inner_w = title_w.max(body_w).min(MAX_W);
let (_, lines) = word_wrap_size(BODY, inner_w);
centered_rect(frame_area, inner_w, lines)
let popup_w = ((inner_w + 2) as u16).min(frame_area.width.saturating_sub(4));
let popup_h = ((lines + 2) as u16).min(frame_area.height.saturating_sub(4));
frame_area.centered(Constraint::Length(popup_w), Constraint::Length(popup_h))
}
-7
View File
@@ -39,13 +39,6 @@ pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) {
(widest_line, lines)
}
pub fn centered_rect(frame: Rect, inner_w: usize, inner_h: usize) -> Rect {
let popup_w = ((inner_w + 2) as u16).min(frame.width.saturating_sub(4));
let popup_h = ((inner_h + 2) as u16).min(frame.height.saturating_sub(4));
use ratatui::layout::Constraint;
frame.centered(Constraint::Length(popup_w), Constraint::Length(popup_h))
}
pub fn top_right_rect(frame: Rect, inner_w: usize, inner_h: usize) -> Rect {
let popup_w = (inner_w + 2) as u16;
let popup_h = (inner_h + 2) as u16;
+40 -10
View File
@@ -13,6 +13,36 @@ use crate::tui::{layout::FocusedArea, theme::THEME};
use super::{popups, search::SearchState, styled_title, WidgetKey};
fn format_last_played(last_played: Option<chrono::DateTime<chrono::Utc>>) -> String {
let Some(dt) = last_played else {
return "Never played".to_string();
};
let secs = chrono::Utc::now()
.signed_duration_since(dt)
.num_seconds()
.max(0) as u64;
match secs {
0..=59 => "Just now".to_string(),
60..=3599 => format!("{} minutes ago", secs / 60),
3600..=86399 => format!("{} hours ago", secs / 3600),
86400..=2591999 => format!("{} days ago", secs / 86400),
2592000..=31535999 => format!("{} months ago", secs / 2592000),
_ => "Over a year ago".to_string(),
}
}
fn loader_color(loader: crate::instance::models::ModLoader) -> ratatui::style::Color {
use crate::instance::models::ModLoader;
use ratatui::style::Color;
match loader {
ModLoader::Vanilla => Color::Green,
ModLoader::Fabric => Color::Rgb(0x71, 0xa5, 0xde),
ModLoader::Forge => Color::Rgb(0xe0, 0x7b, 0x39),
ModLoader::NeoForge => Color::Rgb(0xe0, 0x54, 0x1b),
ModLoader::Quilt => Color::Rgb(0xa6, 0x5c, 0xcb),
}
}
#[derive(Debug, Default)]
pub struct State {
pub instances: Vec<InstanceConfig>,
@@ -190,7 +220,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
let idx = filtered[context.index];
let instance = &state.instances[idx];
let (name_style, info_style, bg) = if context.is_selected {
let (name_style, meta_style, bg) = if context.is_selected {
(
Style::default()
.fg(THEME.colors.row_highlight)
@@ -208,21 +238,21 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
)
};
let indicator = Span::styled(
"\u{258c} ",
Style::default().fg(loader_color(instance.loader)),
);
let name_line = Line::from(vec![
Span::raw(" "),
indicator,
Span::styled(instance.name.as_str(), name_style),
]);
let info_line = Line::from(vec![
let meta_line = Line::from(vec![
Span::raw(" "),
Span::styled(
format!("{} \u{00b7} {}", instance.game_version, instance.loader),
info_style,
),
Span::styled(format_last_played(instance.last_played), meta_style),
]);
let spacer = Line::from("");
let item = Text::from(vec![name_line, info_line, spacer]).style(Style::default().bg(bg));
(item, 3)
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
(item, 2)
});
let list = ListView::new(builder, count).block(block);