feat(content): manage discovery installs incrementally

This commit is contained in:
objz committed 2026-07-26 14:05:49 +02:00
1 parent f26a3542b9
commit 130661f144
9 files changed
+477 -153

No files matched your search

+42 -32
View File
@@ -524,40 +524,39 @@ fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
.sum() .sum()
} }
// 6x3 fallback icon showing a "?" pattern for mods without icons. // 6 columns by 3 terminal rows is physically square with the usual 1:2 cell ratio.
pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> { pub(crate) fn fallback_icon() -> Vec<Vec<IconCell>> {
let b = IconCell { const MASK: [[bool; 6]; 6] = [
[false, true, true, true, true, false],
[true, false, false, false, false, true],
[false, false, false, true, true, false],
[false, false, true, true, false, false],
[false, false, false, false, false, false],
[false, false, true, true, false, false],
];
MASK.chunks_exact(2)
.map(|pair| {
pair[0]
.iter()
.zip(pair[1])
.map(|(&top, bottom)| fallback_cell(top, bottom))
.collect()
})
.collect()
}
fn fallback_cell(top: bool, bottom: bool) -> IconCell {
let background = if top { 150 } else { 45 };
let foreground = if bottom { 150 } else { 45 };
IconCell {
symbol: '\u{2584}', symbol: '\u{2584}',
bg_r: 50, bg_r: background,
bg_g: 50, bg_g: background,
bg_b: 50, bg_b: background,
fg_r: 50, fg_r: foreground,
fg_g: 50, fg_g: foreground,
fg_b: 50, fg_b: foreground,
}; }
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
fg_r: 130,
fg_g: 130,
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
fg_r: 50,
fg_g: 50,
fg_b: 50,
};
vec![
vec![b, tb, tb, tb, tb, b],
vec![b, b, b, bt, bt, b],
vec![b, b, bt, bt, b, b],
]
} }
// 12x6 fallback icon showing a "?" pattern for worlds without icons. // 12x6 fallback icon showing a "?" pattern for worlds without icons.
@@ -636,6 +635,17 @@ mod tests {
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}')); assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
} }
#[test]
fn fallback_icon_is_square_and_contains_a_separate_question_mark_dot() {
let icon = fallback_icon();
assert_eq!(icon.len(), 3);
assert!(icon.iter().all(|row| row.len() == 6));
assert_eq!(icon[2][2].bg_r, 45);
assert_eq!(icon[2][2].fg_r, 150);
assert_eq!(icon[2][3].fg_r, 150);
}
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf { fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp let dir = tmp
.join(instance) .join(instance)
+3
View File
@@ -24,6 +24,8 @@ pub struct VersionInfo {
pub version_number: String, pub version_number: String,
pub game_versions: Vec<String>, pub game_versions: Vec<String>,
pub loaders: Vec<String>, pub loaders: Vec<String>,
#[serde(default)]
pub date_published: String,
pub files: Vec<VersionFile>, pub files: Vec<VersionFile>,
} }
@@ -558,6 +560,7 @@ mod tests {
version_number: "1.0.0".to_owned(), version_number: "1.0.0".to_owned(),
game_versions: vec!["1.21.1".to_owned()], game_versions: vec!["1.21.1".to_owned()],
loaders: vec!["fabric".to_owned()], loaders: vec!["fabric".to_owned()],
date_published: String::new(),
files, files,
} }
} }
+22 -23
View File
@@ -84,14 +84,12 @@ impl App {
self.screenshots_state.drain_pending_entries(); self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads(); self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols(); self.create_screenshot_protocols();
if content_changed { if content_changed
self.reconciliation_for = None; && let Some(instance) = self.instances_state.selected_instance()
if let Some(instance) = self.instances_state.selected_instance() && let Ok(mut results) =
&& let Ok(mut results) = crate::instance::content::reconcile::PENDING_RECONCILIATIONS.lock()
crate::instance::content::reconcile::PENDING_RECONCILIATIONS.lock() {
{ results.retain(|result| result.instance_name != instance.name);
results.retain(|result| result.instance_name != instance.name);
}
} }
self.drain_content_reconciliation(); self.drain_content_reconciliation();
self.ensure_content_reconciliation(content_changed); self.ensure_content_reconciliation(content_changed);
@@ -136,25 +134,26 @@ impl App {
if !changed && self.reconciliation_for.as_deref() == Some(instance.name.as_str()) { if !changed && self.reconciliation_for.as_deref() == Some(instance.name.as_str()) {
return; return;
} }
if self.reconciliation_for.as_deref() != Some(instance.name.as_str()) { let instance_changed = self.reconciliation_for.as_deref() != Some(instance.name.as_str());
if instance_changed {
self.provider_conflict = None; self.provider_conflict = None;
self.dismissed_provider_conflicts.clear(); self.dismissed_provider_conflicts.clear();
self.content_manifest = None;
for discovery in [
&mut self.mods_discovery_state,
&mut self.resource_packs_discovery_state,
&mut self.shaders_discovery_state,
] {
discovery.refresh_installed_manifest(
&crate::instance::ContentManifest::default(),
&crate::storage::InstancePaths::new(
self.instance_manager.instances_dir.join(&instance.name),
)
.minecraft(),
);
}
} }
self.reconciliation_for = Some(instance.name.clone()); self.reconciliation_for = Some(instance.name.clone());
self.content_manifest = None;
for discovery in [
&mut self.mods_discovery_state,
&mut self.resource_packs_discovery_state,
&mut self.shaders_discovery_state,
] {
discovery.refresh_installed_manifest(
&crate::instance::ContentManifest::default(),
&crate::storage::InstancePaths::new(
self.instance_manager.instances_dir.join(&instance.name),
)
.minecraft(),
);
}
if changed { if changed {
crate::instance::content::reconcile::spawn_after_change( crate::instance::content::reconcile::spawn_after_change(
instance, instance,
+60
View File
@@ -155,6 +155,7 @@ impl App {
match delete_content_path(&path) { match delete_content_path(&path) {
Ok(()) => { Ok(()) => {
self.remove_content_path_from_states(&path); self.remove_content_path_from_states(&path);
self.remove_content_path_from_manifest(&path);
} }
Err(e) => { Err(e) => {
tracing::error!("Failed to delete content '{}': {}", name, e); tracing::error!("Failed to delete content '{}': {}", name, e);
@@ -211,6 +212,16 @@ impl App {
self.spawn_active_discovery_versions(); self.spawn_active_discovery_versions();
return Ok(()); return Ok(());
} }
if !search_active && !popup_open && key_event.code == KeyCode::Char('d') {
if let Some(pending) = self
.active_discovery_state_mut()
.and_then(|state| state.pending_installed_delete())
{
confirm_popup::set_pending_content_delete(pending.name, pending.path);
self.focused = FocusedArea::ConfirmDelete;
}
return Ok(());
}
if popup_open && key_event.code == KeyCode::Enter { if popup_open && key_event.code == KeyCode::Enter {
let confirming = self let confirming = self
.active_discovery_state_mut() .active_discovery_state_mut()
@@ -737,6 +748,13 @@ impl App {
crate::net::modrinth::DiscoveryKind::Shader => crate::instance::ContentKind::Shader, crate::net::modrinth::DiscoveryKind::Shader => crate::instance::ContentKind::Shader,
}; };
tokio::spawn(async move { tokio::spawn(async move {
let action = if request.installed_path.is_some() {
format!("Changing {} version", request.project_title)
} else {
format!("Installing {}", request.project_title)
};
let progress = crate::tui::progress::ProgressTask::start(action);
progress.set_sub_action(&request.version.version_number);
let client = crate::net::HttpClient::new(); let client = crate::net::HttpClient::new();
let result = async { let result = async {
tokio::fs::create_dir_all(&destination) tokio::fs::create_dir_all(&destination)
@@ -808,11 +826,18 @@ impl App {
} }
.await .await
.map_err(|error| error.to_string()); .map_err(|error| error.to_string());
if let Err(error) = &result {
progress.fail(error);
} else {
progress.finish();
}
widgets::content::DiscoveryState::push_action_result( widgets::content::DiscoveryState::push_action_result(
&request.pending, &request.pending,
widgets::content::discovery::DiscoveryActionResult::Install { widgets::content::discovery::DiscoveryActionResult::Install {
request_id: request.request_id, request_id: request.request_id,
generation: request.generation,
project_id: request.project_id, project_id: request.project_id,
project_title: request.project_title,
result, result,
}, },
); );
@@ -1047,6 +1072,41 @@ impl App {
self.worlds_state.remove_path(path); self.worlds_state.remove_path(path);
self.screenshots_state.remove_path(path); self.screenshots_state.remove_path(path);
self.logs_state.remove_path(path); self.logs_state.remove_path(path);
self.mods_discovery_state.clear_installed_path(path);
self.resource_packs_discovery_state
.clear_installed_path(path);
self.shaders_discovery_state.clear_installed_path(path);
}
fn remove_content_path_from_manifest(&mut self, path: &std::path::Path) {
let Some(instance) = self.instances_state.selected_instance() else {
return;
};
let instance_paths = crate::storage::InstancePaths::new(
self.instance_manager.instances_dir.join(&instance.name),
);
let minecraft_dir = instance_paths.minecraft();
let Ok(relative_path) = path.strip_prefix(&minecraft_dir) else {
return;
};
if let Some((instance_name, manifest)) = self.content_manifest.as_mut()
&& *instance_name == instance.name
{
manifest.remove(relative_path);
}
if let Err(error) = crate::instance::ContentManifest::update(
&instance_paths.content_manifest(),
|manifest| {
manifest.remove(relative_path);
Ok(())
},
) {
tracing::warn!(
"Failed to remove '{}' from the content manifest: {}",
relative_path.display(),
error
);
}
} }
} }
+190 -41
View File
@@ -97,7 +97,9 @@ pub struct VersionsRequest {
pub struct InstallRequest { pub struct InstallRequest {
pub request_id: u64, pub request_id: u64,
pub generation: u64,
pub project_id: String, pub project_id: String,
pub project_title: String,
pub version: VersionInfo, pub version: VersionInfo,
pub installed_path: Option<PathBuf>, pub installed_path: Option<PathBuf>,
pub pending: PendingActions, pub pending: PendingActions,
@@ -117,7 +119,9 @@ pub enum DiscoveryActionResult {
}, },
Install { Install {
request_id: u64, request_id: u64,
generation: u64,
project_id: String, project_id: String,
project_title: String,
result: Result<InstallCompletion, String>, result: Result<InstallCompletion, String>,
}, },
} }
@@ -302,21 +306,65 @@ impl DiscoveryState {
} }
} }
pub fn selected_is_installed(&self) -> bool {
self.selected_installed_entry().is_some()
}
pub fn pending_installed_delete(
&self,
) -> Option<crate::tui::widgets::content::list::PendingContentDelete> {
let entry = self.selected_installed_entry()?;
Some(crate::tui::widgets::content::list::PendingContentDelete {
name: entry.name.clone(),
path: entry.installed_path.clone()?,
})
}
pub fn clear_installed_path(&mut self, path: &std::path::Path) -> bool {
let Some(entry) = self
.list
.entries
.iter_mut()
.find(|entry| entry.installed_path.as_deref() == Some(path))
else {
return false;
};
entry.installed_path = None;
entry.title_suffix = None;
crate::tui::request_redraw();
true
}
fn selected_installed_entry(&self) -> Option<&ContentEntry> {
let filtered = self.list.filtered_indices();
let index = self
.list
.list_state
.selected
.and_then(|selected| filtered.get(selected))?;
self.list
.entries
.get(*index)
.filter(|entry| entry.installed_path.is_some())
}
pub fn begin_install(&mut self) -> Option<InstallRequest> { pub fn begin_install(&mut self) -> Option<InstallRequest> {
let popup = self.version_popup.as_mut()?; let popup = self.version_popup.as_ref()?;
if popup.loading || popup.installing || !popup.confirming { if popup.loading || popup.installing || !popup.confirming {
return None; return None;
} }
let version = popup.versions.get(popup.selected)?.clone(); let version = popup.versions.get(popup.selected)?.clone();
popup.installing = true; let request = InstallRequest {
popup.error = None;
Some(InstallRequest {
request_id: popup.request_id, request_id: popup.request_id,
generation: self.generation,
project_id: popup.project_id.clone(), project_id: popup.project_id.clone(),
project_title: popup.project_title.clone(),
version, version,
installed_path: popup.installed_path.clone(), installed_path: popup.installed_path.clone(),
pending: self.pending_actions.clone(), pending: self.pending_actions.clone(),
}) };
self.version_popup = None;
Some(request)
} }
pub fn begin_confirmation(&mut self) -> bool { pub fn begin_confirmation(&mut self) -> bool {
@@ -447,47 +495,49 @@ impl DiscoveryState {
} }
DiscoveryActionResult::Install { DiscoveryActionResult::Install {
request_id, request_id,
generation,
project_id, project_id,
project_title,
result, result,
} => { } => match result {
let Some(popup) = self.version_popup.as_mut().filter(|popup| { Ok(completion) => {
popup.request_id == request_id && popup.project_id == project_id if generation == self.generation
}) else { && let Some(entry) = self
continue;
};
popup.installing = false;
popup.confirming = false;
match result {
Ok(completion) => {
if let Some(entry) = self
.list .list
.entries .entries
.iter_mut() .iter_mut()
.find(|entry| entry.file_stem == project_id) .find(|entry| entry.file_stem == project_id)
{ {
entry.title_suffix = Some("Installed".to_owned()); entry.title_suffix = Some("Installed".to_owned());
entry.installed_path = Some(completion.path.clone()); entry.installed_path = Some(completion.path.clone());
}
let action = if completion.skipped {
"already installed"
} else if completion.replaced {
"version changed"
} else {
"installed"
};
crate::tui::error_buffer::push_error(
crate::tui::error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::INFO,
message: format!("{}: {action}", popup.project_title),
pushed_at: std::time::Instant::now(),
},
);
self.version_popup = None;
} }
Err(error) => popup.error = Some(error), let action = if completion.skipped {
"already installed"
} else if completion.replaced {
"version changed"
} else {
"installed"
};
crate::tui::error_buffer::push_error(
crate::tui::error_buffer::ErrorEvent {
id: request_id,
level: tracing::Level::INFO,
message: format!("{project_title}: {action}"),
pushed_at: std::time::Instant::now(),
},
);
} }
} Err(error) => {
crate::tui::error_buffer::push_error(
crate::tui::error_buffer::ErrorEvent {
id: request_id,
level: tracing::Level::ERROR,
message: format!("{project_title}: {error}"),
pushed_at: std::time::Instant::now(),
},
);
}
},
} }
} }
} }
@@ -522,6 +572,14 @@ impl DiscoveryState {
pub fn handle_key(key_event: &KeyEvent, state: &mut DiscoveryState) -> bool { pub fn handle_key(key_event: &KeyEvent, state: &mut DiscoveryState) -> bool {
if let Some(popup) = state.version_popup.as_mut() { if let Some(popup) = state.version_popup.as_mut() {
if popup.confirming
&& matches!(key_event.code, KeyCode::Left | KeyCode::Char('h'))
&& !popup.installing
{
popup.confirming = false;
popup.error = None;
return true;
}
match key_event.code { match key_event.code {
KeyCode::Esc if !popup.installing => state.version_popup = None, KeyCode::Esc if !popup.installing => state.version_popup = None,
KeyCode::Char('j') | KeyCode::Down KeyCode::Char('j') | KeyCode::Down
@@ -650,6 +708,7 @@ mod tests {
version_number: id.to_owned(), version_number: id.to_owned(),
game_versions: vec!["1.21.1".to_owned()], game_versions: vec!["1.21.1".to_owned()],
loaders: vec!["fabric".to_owned()], loaders: vec!["fabric".to_owned()],
date_published: "2026-01-02T12:00:00Z".to_owned(),
files: Vec::new(), files: Vec::new(),
} }
} }
@@ -747,7 +806,7 @@ mod tests {
} }
#[test] #[test]
fn successful_install_marks_the_project_and_closes_the_popup() { fn confirmation_can_return_to_version_selection() {
let project = DiscoveryProject { let project = DiscoveryProject {
id: "project".to_owned(), id: "project".to_owned(),
slug: "project".to_owned(), slug: "project".to_owned(),
@@ -763,9 +822,100 @@ mod tests {
let request = state.begin_versions().unwrap(); let request = state.begin_versions().unwrap();
DiscoveryState::push_action_result( DiscoveryState::push_action_result(
&request.pending, &request.pending,
DiscoveryActionResult::Install { DiscoveryActionResult::Versions {
request_id: request.request_id, request_id: request.request_id,
project_id: request.project_id, project_id: request.project_id,
result: Ok(vec![version("1.0.0")]),
},
);
state.drain_pending();
assert!(state.begin_confirmation());
handle_key(
&KeyEvent::new(KeyCode::Char('h'), KeyModifiers::NONE),
&mut state,
);
assert!(!state.version_popup.as_ref().unwrap().confirming);
assert!(state.version_popup.is_some());
}
#[test]
fn discovery_delete_only_clears_the_matching_installed_badge() {
let first_path = PathBuf::from("mods/first.jar");
let second_path = PathBuf::from("mods/second.jar");
let project = |id: &str| DiscoveryProject {
id: id.to_owned(),
slug: id.to_owned(),
title: id.to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state
.list
.entries
.push(project_entry(project("first"), Some(first_path.clone())));
state
.list
.entries
.push(project_entry(project("second"), Some(second_path.clone())));
state.list.list_state.selected = Some(0);
let pending = state.pending_installed_delete().unwrap();
assert_eq!(pending.path, first_path);
assert!(state.clear_installed_path(&pending.path));
assert_eq!(state.list.entries.len(), 2);
assert!(state.list.entries[0].installed_path.is_none());
assert!(state.list.entries[0].title_suffix.is_none());
assert_eq!(
state.list.entries[1].installed_path.as_deref(),
Some(second_path.as_path())
);
assert_eq!(
state.list.entries[1].title_suffix.as_deref(),
Some("Installed")
);
assert!(state.pending_installed_delete().is_none());
}
#[test]
fn successful_install_marks_the_project_and_closes_the_popup() {
let project = DiscoveryProject {
id: "project".to_owned(),
slug: "project".to_owned(),
title: "Project".to_owned(),
description: String::new(),
downloads: 0,
icon_url: None,
icon_bytes: None,
};
let mut state = DiscoveryState::new(DiscoveryKind::Mod);
state.list.entries.push(project_entry(project, None));
state.list.list_state.selected = Some(0);
let versions_request = state.begin_versions().unwrap();
DiscoveryState::push_action_result(
&versions_request.pending,
DiscoveryActionResult::Versions {
request_id: versions_request.request_id,
project_id: versions_request.project_id,
result: Ok(vec![version("1.0.0")]),
},
);
state.drain_pending();
assert!(state.begin_confirmation());
let install = state.begin_install().unwrap();
assert!(state.version_popup.is_none());
DiscoveryState::push_action_result(
&install.pending,
DiscoveryActionResult::Install {
request_id: install.request_id,
generation: install.generation,
project_id: install.project_id,
project_title: install.project_title,
result: Ok(InstallCompletion { result: Ok(InstallCompletion {
path: PathBuf::from("mods/project.jar"), path: PathBuf::from("mods/project.jar"),
replaced: false, replaced: false,
@@ -775,7 +925,6 @@ mod tests {
); );
state.drain_pending(); state.drain_pending();
assert!(state.version_popup.is_none()); assert!(state.version_popup.is_none());
assert_eq!( assert_eq!(
state.list.entries[0].title_suffix.as_deref(), state.list.entries[0].title_suffix.as_deref(),
+129 -29
View File
@@ -211,10 +211,25 @@ pub fn render(
block = block.title_top(sl); block = block.title_top(sl);
} }
let discovery_can_delete = match tab {
ContentTab::Mods => mods_discovery_state.selected_is_installed(),
ContentTab::ResourcePacks => resource_packs_discovery_state.selected_is_installed(),
ContentTab::Shaders => shaders_discovery_state.selected_is_installed(),
_ => false,
};
// keybinds change depending on which tab is active and whether // keybinds change depending on which tab is active and whether
// the content panel or instances panel has focus // the content panel or instances panel has focus
let kb: Option<&[(&str, &str)]> = if is_focused { let kb: Option<&[(&str, &str)]> = if is_focused {
Some(match (mode, tab) { Some(match (mode, tab) {
(ContentMode::Discover, _) if discovery_can_delete => &[
("j/k", " navigate"),
("i", " versions"),
("d", " delete"),
("h/l", " tabs"),
("/", " search"),
("Tab", " installed"),
],
(ContentMode::Discover, _) => &[ (ContentMode::Discover, _) => &[
("j/k", " navigate"), ("j/k", " navigate"),
("i", " versions"), ("i", " versions"),
@@ -531,18 +546,16 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
let Some(popup) = state.version_popup.as_ref() else { let Some(popup) = state.version_popup.as_ref() else {
return; return;
}; };
let [_, vertical, _] = Layout::vertical([ let desired_height = version_popup_height(
Constraint::Percentage(10), popup.versions.len(),
Constraint::Percentage(80), popup.confirming,
Constraint::Percentage(10), popup.loading || popup.installing,
]) popup.error.is_some(),
.areas(area); );
let [_, popup_area, _] = Layout::horizontal([ let popup_area = area.centered(
Constraint::Percentage(12), Constraint::Percentage(50),
Constraint::Percentage(76), Constraint::Length(desired_height.min(area.height.saturating_sub(2))),
Constraint::Percentage(12), );
])
.areas(vertical);
let theme = THEME.as_ref(); let theme = THEME.as_ref();
let title = popup.title(); let title = popup.title();
let loading = popup.loading; let loading = popup.loading;
@@ -555,7 +568,21 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
.get(selected) .get(selected)
.map(|version| version.version_number.clone()) .map(|version| version.version_number.clone())
.unwrap_or_default(); .unwrap_or_default();
let project_title = popup.project_title.clone(); let minecraft_versions = popup
.versions
.get(selected)
.map(|version| confirmation_values(&version.game_versions))
.unwrap_or_else(|| "Unknown".to_owned());
let loaders = popup
.versions
.get(selected)
.map(|version| confirmation_loaders(&version.loaders))
.unwrap_or_else(|| "Unknown".to_owned());
let release_date = popup
.versions
.get(selected)
.map(|version| confirmation_release_date(&version.date_published))
.unwrap_or_else(|| "Unknown".to_owned());
let replacing = popup.installed_path.is_some(); let replacing = popup.installed_path.is_some();
let items = popup let items = popup
.versions .versions
@@ -564,20 +591,24 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
ListItem::new(discovery_version_label(version)).style(Style::default().fg(theme.text())) ListItem::new(discovery_version_label(version)).style(Style::default().fg(theme.text()))
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let keybinds = if confirming {
crate::tui::widgets::popups::keybind_line(&[
("h", " back"),
("Enter", if replacing { " change" } else { " install" }),
])
} else {
crate::tui::widgets::popups::keybind_line(&[
("j/k", " navigate"),
("Enter", " continue"),
("Esc", " close"),
])
};
let popup = crate::tui::widgets::popups::base::PopupFrame { let popup = crate::tui::widgets::popups::base::PopupFrame {
title: styled_title(&title, false), title: styled_title(&title, false),
border_color: theme.accent(), border_color: theme.accent(),
bg: Some(theme.surface()), bg: Some(theme.surface()),
keybinds: Some(crate::tui::widgets::popups::keybind_line(if confirming { keybinds: Some(keybinds),
&[("Enter", " confirm"), ("Esc", " cancel")]
} else {
&[
("j/k", " navigate"),
("Enter", " continue"),
("Esc", " close"),
]
})),
search_line: None, search_line: None,
content: Box::new(move |area, buffer| { content: Box::new(move |area, buffer| {
if installing { if installing {
@@ -594,13 +625,16 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
.wrap(Wrap { trim: true }) .wrap(Wrap { trim: true })
.render(area, buffer); .render(area, buffer);
} else if confirming { } else if confirming {
let action = if replacing { "Change" } else { "Install" }; crate::tui::widgets::popups::base::render_summary(
Paragraph::new(format!( &[
"{action} {project_title} version {selected_version}?\n\nThe file is changed only after the download succeeds." ("Version", selected_version.as_str()),
)) ("Minecraft", minecraft_versions.as_str()),
.style(Style::default().fg(THEME.as_ref().text())) ("Loader", loaders.as_str()),
.wrap(Wrap { trim: true }) ("Released", release_date.as_str()),
.render(area, buffer); ],
area,
buffer,
);
} else if items.is_empty() { } else if items.is_empty() {
Paragraph::new("No compatible versions found.") Paragraph::new("No compatible versions found.")
.style(Style::default().fg(THEME.as_ref().text_dim())) .style(Style::default().fg(THEME.as_ref().text_dim()))
@@ -618,6 +652,49 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
frame.render_widget(popup, popup_area); frame.render_widget(popup, popup_area);
} }
fn version_popup_height(version_count: usize, confirming: bool, compact: bool, error: bool) -> u16 {
if confirming || error {
8
} else if compact {
5
} else {
(version_count as u16).saturating_add(2).clamp(6, 18)
}
}
fn confirmation_values(values: &[String]) -> String {
if values.is_empty() {
"Unknown".to_owned()
} else {
values.join(", ")
}
}
fn confirmation_loaders(loaders: &[String]) -> String {
let loaders = loaders
.iter()
.map(|loader| match loader.as_str() {
"fabric" => "Fabric",
"forge" => "Forge",
"neoforge" => "NeoForge",
"quilt" => "Quilt",
"minecraft" => "Minecraft",
other => other,
})
.map(str::to_owned)
.collect::<Vec<_>>();
confirmation_values(&loaders)
}
fn confirmation_release_date(value: &str) -> String {
if value.is_empty() {
return "Unknown".to_owned();
}
chrono::DateTime::parse_from_rfc3339(value)
.map(|date| date.format("%Y-%m-%d").to_string())
.unwrap_or_else(|_| value.to_owned())
}
fn discovery_version_label(version: &crate::net::modrinth::VersionInfo) -> String { fn discovery_version_label(version: &crate::net::modrinth::VersionInfo) -> String {
version.version_number.clone() version.version_number.clone()
} }
@@ -768,9 +845,32 @@ mod tests {
version_number: "3.2.4-fabric-26.1".to_owned(), version_number: "3.2.4-fabric-26.1".to_owned(),
game_versions: vec![], game_versions: vec![],
loaders: vec![], loaders: vec![],
date_published: String::new(),
files: vec![], files: vec![],
}; };
assert_eq!(discovery_version_label(&version), "3.2.4-fabric-26.1"); assert_eq!(discovery_version_label(&version), "3.2.4-fabric-26.1");
} }
#[test]
fn discovery_version_popup_uses_compact_heights() {
assert_eq!(version_popup_height(1, false, false, false), 6);
assert_eq!(version_popup_height(100, false, false, false), 18);
assert_eq!(version_popup_height(1, true, false, false), 8);
assert_eq!(version_popup_height(0, false, true, false), 5);
assert_eq!(version_popup_height(0, false, false, true), 8);
}
#[test]
fn confirmation_metadata_is_human_readable() {
assert_eq!(
confirmation_loaders(&["fabric".to_owned(), "neoforge".to_owned()]),
"Fabric, NeoForge"
);
assert_eq!(
confirmation_release_date("2026-07-26T14:30:00Z"),
"2026-07-26"
);
assert_eq!(confirmation_values(&[]), "Unknown");
}
} }
+17 -2
View File
@@ -6,8 +6,8 @@ use ratatui::{
buffer::Buffer, buffer::Buffer,
layout::{Alignment, Rect}, layout::{Alignment, Rect},
style::{Color, Style}, style::{Color, Style},
text::Line, text::{Line, Span},
widgets::{Block, Clear, Widget}, widgets::{Block, Clear, Paragraph, Widget},
}; };
use crate::config::theme::BORDER_STYLE; use crate::config::theme::BORDER_STYLE;
@@ -50,3 +50,18 @@ impl<'a> Widget for PopupFrame<'a> {
(self.content)(inner, buf); (self.content)(inner, buf);
} }
} }
pub fn render_summary(rows: &[(&str, &str)], area: Rect, buf: &mut Buffer) {
let theme = crate::config::theme::THEME.as_ref();
let label_style = Style::default().fg(theme.text_dim());
let lines = rows
.iter()
.map(|(label, value)| {
Line::from(vec![
Span::styled(format!("{label}: "), label_style),
Span::styled(*value, Style::default().fg(theme.text())),
])
})
.collect::<Vec<_>>();
Paragraph::new(lines).render(area, buf);
}
@@ -301,6 +301,7 @@ mod tests {
version_number: "1.0.0".into(), version_number: "1.0.0".into(),
game_versions: vec!["1.20.1".into()], game_versions: vec!["1.20.1".into()],
loaders: vec!["fabric".into()], loaders: vec!["fabric".into()],
date_published: String::new(),
files: vec![], files: vec![],
}, },
VersionInfo { VersionInfo {
@@ -310,6 +311,7 @@ mod tests {
version_number: "0.9.0".into(), version_number: "0.9.0".into(),
game_versions: vec!["1.20.1".into()], game_versions: vec!["1.20.1".into()],
loaders: vec!["fabric".into()], loaders: vec!["fabric".into()],
date_published: String::new(),
files: vec![], files: vec![],
}, },
]); ]);
+12 -26
View File
@@ -8,7 +8,7 @@ use super::state::{
use crate::config::theme::THEME; use crate::config::theme::THEME;
use crate::instance::models::ModLoader; use crate::instance::models::ModLoader;
use crate::tui::app::FocusedArea; use crate::tui::app::FocusedArea;
use crate::tui::widgets::popups::base::PopupFrame; use crate::tui::widgets::popups::base::{PopupFrame, render_summary};
use ratatui::{ use ratatui::{
Frame, Frame,
layout::{Constraint, Direction, Layout, Rect}, layout::{Constraint, Direction, Layout, Rect},
@@ -294,7 +294,6 @@ fn render_loader_version_step(state: &WizardState, area: Rect, buf: &mut ratatui
} }
fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) { fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let game_version = state let game_version = state
.selected_version() .selected_version()
.map(|version| version.id.as_str()) .map(|version| version.id.as_str())
@@ -307,30 +306,17 @@ fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe
.selected_loader_version() .selected_loader_version()
.unwrap_or_else(|| "<not selected>".to_string()) .unwrap_or_else(|| "<not selected>".to_string())
}; };
let loader = loader.to_string();
let label_style = Style::default().fg(theme.text_dim()); render_summary(
&[
Paragraph::new(vec![ ("Name", state.name_state.value()),
Line::from(vec![ ("MC", game_version),
Span::styled("Name: ", label_style), ("Loader", &loader),
Span::raw(state.name_state.value()), ("Loader version", &loader_version),
]), ],
Line::from(vec![ area,
Span::styled("MC: ", label_style), buf,
Span::raw(game_version), );
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader.to_string()),
]),
Line::from(vec![
Span::styled("Loader version: ", label_style),
Span::raw(loader_version),
]),
])
.style(Style::default().fg(theme.text()))
.wrap(Wrap { trim: true })
.render(area, buf);
} }
#[cfg(test)] #[cfg(test)]