feat(content): manage required mod dependencies
This commit is contained in:
1 parent
de6defa1ff
commit
3b26581af5
27 files changed
+2487
-75
No files matched your search
+9
-1
@@ -7,7 +7,7 @@ use ratatui::{
|
||||
use std::time::Duration;
|
||||
|
||||
use super::Tui;
|
||||
use super::app::{App, PENDING_INSTANCES};
|
||||
use super::app::{App, FocusedArea, PENDING_INSTANCES};
|
||||
use super::widgets::{self, popups::import_modpack, popups::new_instance};
|
||||
use crate::feedback::errors as error_buffer;
|
||||
use crate::feedback::progress;
|
||||
@@ -44,6 +44,7 @@ impl App {
|
||||
let mut local_streamed = false;
|
||||
let mut content_changed = false;
|
||||
let mut toggles = Vec::new();
|
||||
let mut orphan_cleanup = None;
|
||||
for (local, discovery) in [
|
||||
(&mut self.mods_state, &mut self.mods_discovery_state),
|
||||
(
|
||||
@@ -60,10 +61,17 @@ impl App {
|
||||
local.request_image_loads(&self.picker);
|
||||
local.drain_image_loads(&self.picker);
|
||||
discovery.drain_pending();
|
||||
if self.focused == FocusedArea::Content {
|
||||
orphan_cleanup = orphan_cleanup.or_else(|| discovery.take_orphan_cleanup());
|
||||
}
|
||||
discovery.list.drain_pending();
|
||||
discovery.list.request_image_loads(&self.picker);
|
||||
discovery.list.drain_image_loads(&self.picker);
|
||||
}
|
||||
if let Some(paths) = orphan_cleanup {
|
||||
widgets::popups::confirm::set_pending_orphan_dependencies(paths);
|
||||
self.focused = FocusedArea::ConfirmDelete;
|
||||
}
|
||||
self.worlds_state.drain_pending();
|
||||
self.worlds_state.drain_watcher();
|
||||
self.worlds_state.request_image_loads(&self.picker);
|
||||
|
||||
+164
-16
@@ -198,11 +198,16 @@ impl App {
|
||||
}
|
||||
FocusedArea::Settings
|
||||
}
|
||||
Some(confirm_popup::ConfirmTarget::Content { name, path }) => {
|
||||
Some(confirm_popup::ConfirmTarget::Content { name, path, .. }) => {
|
||||
let orphaned = self.orphan_dependencies_after_removing(&path);
|
||||
match delete_content_path(&path) {
|
||||
Ok(()) => {
|
||||
self.remove_content_path_from_states(&path);
|
||||
self.remove_content_path_from_manifest(&path);
|
||||
if !orphaned.is_empty() {
|
||||
confirm_popup::set_pending_orphan_dependencies(orphaned);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to delete content '{}': {}", name, e);
|
||||
@@ -210,6 +215,22 @@ impl App {
|
||||
}
|
||||
FocusedArea::Content
|
||||
}
|
||||
Some(confirm_popup::ConfirmTarget::OrphanDependencies { paths }) => {
|
||||
for path in paths {
|
||||
match delete_content_path(&path) {
|
||||
Ok(()) => {
|
||||
self.remove_content_path_from_states(&path);
|
||||
self.remove_content_path_from_manifest(&path);
|
||||
}
|
||||
Err(error) => tracing::error!(
|
||||
"Failed to remove unused dependency '{}': {}",
|
||||
path.display(),
|
||||
error
|
||||
),
|
||||
}
|
||||
}
|
||||
FocusedArea::Content
|
||||
}
|
||||
None => FocusedArea::Instances,
|
||||
};
|
||||
confirm_popup::clear_pending();
|
||||
@@ -219,6 +240,9 @@ impl App {
|
||||
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
|
||||
let focus_after = match confirm_popup::pending_target() {
|
||||
Some(confirm_popup::ConfirmTarget::Content { .. }) => FocusedArea::Content,
|
||||
Some(confirm_popup::ConfirmTarget::OrphanDependencies { .. }) => {
|
||||
FocusedArea::Content
|
||||
}
|
||||
Some(confirm_popup::ConfirmTarget::Account { .. }) => FocusedArea::Account,
|
||||
Some(confirm_popup::ConfirmTarget::ConfigProfile { .. }) => {
|
||||
FocusedArea::Settings
|
||||
@@ -271,8 +295,7 @@ impl App {
|
||||
.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;
|
||||
self.confirm_content_delete(pending);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -289,8 +312,15 @@ impl App {
|
||||
.is_some_and(|popup| popup.confirming);
|
||||
if confirming {
|
||||
self.spawn_active_discovery_install();
|
||||
} else if let Some(state) = self.active_discovery_state_mut() {
|
||||
state.begin_confirmation();
|
||||
} else {
|
||||
let resolve_dependencies = self
|
||||
.active_discovery_state_mut()
|
||||
.is_some_and(|state| state.kind == crate::instance::ContentKind::Mod);
|
||||
if resolve_dependencies {
|
||||
self.spawn_active_discovery_dependencies();
|
||||
} else if let Some(state) = self.active_discovery_state_mut() {
|
||||
state.begin_confirmation();
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -318,8 +348,7 @@ impl App {
|
||||
&& !self.logs_state.viewer_search.active
|
||||
{
|
||||
if let Some(pending) = self.logs_state.pending_delete() {
|
||||
confirm_popup::set_pending_content_delete(pending.name, pending.path);
|
||||
self.focused = FocusedArea::ConfirmDelete;
|
||||
self.confirm_content_delete(pending);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -329,8 +358,7 @@ impl App {
|
||||
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
|
||||
if key_event.code == KeyCode::Char('d') && !self.screenshots_state.search.active {
|
||||
if let Some(pending) = self.screenshots_state.pending_delete() {
|
||||
confirm_popup::set_pending_content_delete(pending.name, pending.path);
|
||||
self.focused = FocusedArea::ConfirmDelete;
|
||||
self.confirm_content_delete(pending);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -340,8 +368,7 @@ impl App {
|
||||
} else if self.content_tab == widgets::content::ContentTab::Worlds {
|
||||
if key_event.code == KeyCode::Char('d') && !self.worlds_state.search.active {
|
||||
if let Some(pending) = self.worlds_state.pending_delete() {
|
||||
confirm_popup::set_pending_content_delete(pending.name, pending.path);
|
||||
self.focused = FocusedArea::ConfirmDelete;
|
||||
self.confirm_content_delete(pending);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -361,8 +388,7 @@ impl App {
|
||||
if let Some(state) = state {
|
||||
if key_event.code == KeyCode::Char('d') && !state.search.active {
|
||||
if let Some(pending) = state.pending_delete() {
|
||||
confirm_popup::set_pending_content_delete(pending.name, pending.path);
|
||||
self.focused = FocusedArea::ConfirmDelete;
|
||||
self.confirm_content_delete(pending);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -724,6 +750,48 @@ impl App {
|
||||
self.spawn_discovery_versions_request(instance, kind, request);
|
||||
}
|
||||
|
||||
fn spawn_active_discovery_dependencies(&mut self) {
|
||||
let Some(instance) = self.instances_state.selected_instance().cloned() else {
|
||||
return;
|
||||
};
|
||||
let Some(request) = self
|
||||
.active_discovery_state_mut()
|
||||
.and_then(|state| state.begin_dependency_resolution())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let paths = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
let result = async {
|
||||
let manifest = crate::instance::ContentManifest::load(&paths.content_manifest())
|
||||
.map_err(|error| crate::net::NetError::Parse(error.to_string()))?;
|
||||
let registry = crate::instance::content::provider::ProviderRegistry::configured(
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
crate::instance::content::dependencies::resolve(
|
||||
®istry,
|
||||
&manifest,
|
||||
&paths.minecraft(),
|
||||
&instance,
|
||||
request.root,
|
||||
)
|
||||
.await
|
||||
}
|
||||
.await
|
||||
.map_err(|error| error.to_string());
|
||||
widgets::content::DiscoveryState::push_action_result(
|
||||
&request.pending,
|
||||
widgets::content::discovery::DiscoveryActionResult::Dependencies {
|
||||
request_id: request.request_id,
|
||||
project_id: request.project_id,
|
||||
result,
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_discovery_versions_request(
|
||||
&self,
|
||||
instance: crate::instance::InstanceConfig,
|
||||
@@ -921,9 +989,8 @@ impl App {
|
||||
.join(&instance.name)
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
.join(kind.directory());
|
||||
let instance_paths = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
);
|
||||
let instances_dir = self.instance_manager.instances_dir.clone();
|
||||
let instance_paths = crate::storage::InstancePaths::new(instances_dir.join(&instance.name));
|
||||
let manifest_path = instance_paths.content_manifest();
|
||||
let minecraft_dir = instance_paths.minecraft();
|
||||
tokio::spawn(async move {
|
||||
@@ -941,6 +1008,25 @@ impl App {
|
||||
.map_err(crate::net::NetError::from)?;
|
||||
let registry =
|
||||
crate::instance::content::provider::ProviderRegistry::configured(client);
|
||||
if let Some(plan) = &request.dependency_plan {
|
||||
let installed = crate::instance::content::dependencies::install(
|
||||
®istry,
|
||||
&manifest_path,
|
||||
&minecraft_dir,
|
||||
&destination,
|
||||
plan,
|
||||
request.request_id,
|
||||
)
|
||||
.await?;
|
||||
return Ok::<_, crate::net::NetError>(
|
||||
widgets::content::discovery::InstallCompletion {
|
||||
path: installed.root_path,
|
||||
replaced: installed.replaced,
|
||||
skipped: installed.skipped,
|
||||
orphaned_dependencies: installed.orphaned_dependencies,
|
||||
},
|
||||
);
|
||||
}
|
||||
let provider = registry.get(&request.provider).ok_or_else(|| {
|
||||
crate::net::NetError::Parse(format!(
|
||||
"{} content provider is unavailable",
|
||||
@@ -979,6 +1065,9 @@ impl App {
|
||||
version_id: request.version.id.clone(),
|
||||
},
|
||||
},
|
||||
provider_aliases: Vec::new(),
|
||||
required_dependencies: Vec::new(),
|
||||
automatic_dependency: false,
|
||||
};
|
||||
crate::instance::ContentManifest::update(&manifest_path, |manifest| {
|
||||
if let Some(old_path) = request.installed_path.as_ref()
|
||||
@@ -1003,6 +1092,7 @@ impl App {
|
||||
path,
|
||||
replaced,
|
||||
skipped,
|
||||
orphaned_dependencies: Vec::new(),
|
||||
})
|
||||
}
|
||||
.await
|
||||
@@ -1011,6 +1101,11 @@ impl App {
|
||||
progress.fail(error);
|
||||
} else {
|
||||
progress.finish();
|
||||
crate::instance::content::reconcile::spawn_after_change(
|
||||
instance,
|
||||
instances_dir,
|
||||
crate::net::HttpClient::new(),
|
||||
);
|
||||
}
|
||||
widgets::content::DiscoveryState::push_action_result(
|
||||
&request.pending,
|
||||
@@ -1286,6 +1381,59 @@ impl App {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn confirm_content_delete(&mut self, pending: widgets::content::list::PendingContentDelete) {
|
||||
let dependents = self
|
||||
.content_manifest_for_path(&pending.path)
|
||||
.map(|(manifest, relative_path, _)| {
|
||||
manifest
|
||||
.dependent_paths(&relative_path)
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
path.file_stem()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("mod")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
confirm_popup::set_pending_managed_content_delete(pending.name, pending.path, dependents);
|
||||
self.focused = FocusedArea::ConfirmDelete;
|
||||
}
|
||||
|
||||
fn orphan_dependencies_after_removing(
|
||||
&self,
|
||||
path: &std::path::Path,
|
||||
) -> Vec<std::path::PathBuf> {
|
||||
self.content_manifest_for_path(path)
|
||||
.map(|(manifest, relative_path, minecraft_dir)| {
|
||||
manifest
|
||||
.orphaned_dependencies_after_removing(&relative_path)
|
||||
.into_iter()
|
||||
.map(|relative| minecraft_dir.join(relative))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn content_manifest_for_path(
|
||||
&self,
|
||||
path: &std::path::Path,
|
||||
) -> Option<(
|
||||
crate::instance::ContentManifest,
|
||||
std::path::PathBuf,
|
||||
std::path::PathBuf,
|
||||
)> {
|
||||
let instance = self.instances_state.selected_instance()?;
|
||||
let paths = crate::storage::InstancePaths::new(
|
||||
self.instance_manager.instances_dir.join(&instance.name),
|
||||
);
|
||||
let minecraft_dir = paths.minecraft();
|
||||
let relative_path = path.strip_prefix(&minecraft_dir).ok()?.to_owned();
|
||||
let manifest = crate::instance::ContentManifest::load(&paths.content_manifest()).ok()?;
|
||||
Some((manifest, relative_path, minecraft_dir))
|
||||
}
|
||||
|
||||
fn remove_content_path_from_states(&mut self, path: &std::path::Path) {
|
||||
self.mods_state.remove_path(path);
|
||||
self.resource_packs_state.remove_path(path);
|
||||
|
||||
+153
-1
@@ -1,7 +1,11 @@
|
||||
use crossterm::event::{KeyCode, MouseEventKind};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::harness::UiHarness;
|
||||
use crate::instance::ProviderProject;
|
||||
use crate::instance::content::entry::ContentEntry;
|
||||
use crate::instance::{
|
||||
ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution,
|
||||
};
|
||||
use crate::net::modrinth::DiscoveryProject;
|
||||
use crate::tui::{
|
||||
app::{FocusedArea, ProviderConflictState},
|
||||
@@ -160,6 +164,151 @@ fn confirmed_screenshot_delete_removes_state_and_file() {
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
fn managed_mod_record(
|
||||
path: &str,
|
||||
project_id: &str,
|
||||
automatic_dependency: bool,
|
||||
required_dependencies: Vec<ProviderProject>,
|
||||
) -> ContentFileRecord {
|
||||
ContentFileRecord {
|
||||
relative_path: PathBuf::from(path),
|
||||
kind: ContentKind::Mod,
|
||||
enabled: true,
|
||||
fingerprint: FileFingerprint {
|
||||
size: 1,
|
||||
modified_ns: 1,
|
||||
hashes: Default::default(),
|
||||
},
|
||||
resolution: Resolution::Resolved {
|
||||
project: ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: project_id.to_owned(),
|
||||
version_id: format!("{project_id}-version"),
|
||||
},
|
||||
},
|
||||
provider_aliases: Vec::new(),
|
||||
required_dependencies,
|
||||
automatic_dependency,
|
||||
}
|
||||
}
|
||||
|
||||
fn content_entry(name: &str, path: PathBuf) -> ContentEntry {
|
||||
ContentEntry {
|
||||
file_stem: name.to_owned(),
|
||||
name: name.to_owned(),
|
||||
source_slug: None,
|
||||
installed_path: Some(path.clone()),
|
||||
provider_project: None,
|
||||
title_suffix: None,
|
||||
footer_label: None,
|
||||
description: String::new(),
|
||||
enabled: true,
|
||||
icon_bytes: None,
|
||||
provider_icon: false,
|
||||
provider_description: false,
|
||||
path,
|
||||
icon_lines: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_mod_offers_its_unused_dependency_chain() {
|
||||
let mut ui = UiHarness::new();
|
||||
ui.add_instance("Dependencies");
|
||||
let minecraft = ui
|
||||
.instance_path("Dependencies")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let root_path = minecraft.join("mods/root.jar");
|
||||
let library_path = minecraft.join("mods/library.jar");
|
||||
std::fs::create_dir_all(root_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&root_path, b"r").unwrap();
|
||||
std::fs::write(&library_path, b"l").unwrap();
|
||||
let dependency = ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: "library".to_owned(),
|
||||
version_id: "library-version".to_owned(),
|
||||
};
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![
|
||||
managed_mod_record("mods/root.jar", "root", false, vec![dependency]),
|
||||
managed_mod_record("mods/library.jar", "library", true, Vec::new()),
|
||||
],
|
||||
}
|
||||
.save(&crate::storage::InstancePaths::new(ui.instance_path("Dependencies")).content_manifest())
|
||||
.unwrap();
|
||||
ui.app.mods_state.entries = vec![content_entry("Root", root_path.clone())];
|
||||
ui.app.mods_state.list_state.selected = Some(0);
|
||||
ui.app.focused = FocusedArea::Content;
|
||||
ui.app.content_tab = ContentTab::Mods;
|
||||
|
||||
ui.key(KeyCode::Char('d'));
|
||||
ui.key(KeyCode::Enter);
|
||||
|
||||
assert!(!root_path.exists());
|
||||
assert!(library_path.exists());
|
||||
assert!(matches!(
|
||||
confirm::pending_target(),
|
||||
Some(confirm::ConfirmTarget::OrphanDependencies { paths })
|
||||
if paths == vec![library_path.clone()]
|
||||
));
|
||||
assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete);
|
||||
|
||||
ui.key(KeyCode::Enter);
|
||||
|
||||
assert!(!library_path.exists());
|
||||
assert_eq!(ui.app.focused, FocusedArea::Content);
|
||||
let manifest = ContentManifest::load(
|
||||
&crate::storage::InstancePaths::new(ui.instance_path("Dependencies")).content_manifest(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(manifest.files.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_required_library_warns_but_can_continue() {
|
||||
let mut ui = UiHarness::new();
|
||||
ui.add_instance("Required");
|
||||
let minecraft = ui
|
||||
.instance_path("Required")
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let library_path = minecraft.join("mods/library.jar");
|
||||
std::fs::create_dir_all(library_path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&library_path, b"l").unwrap();
|
||||
ContentManifest {
|
||||
version: 1,
|
||||
files: vec![
|
||||
managed_mod_record(
|
||||
"mods/root.jar",
|
||||
"root",
|
||||
false,
|
||||
vec![ProviderProject {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: "library".to_owned(),
|
||||
version_id: "library-version".to_owned(),
|
||||
}],
|
||||
),
|
||||
managed_mod_record("mods/library.jar", "library", true, Vec::new()),
|
||||
],
|
||||
}
|
||||
.save(&crate::storage::InstancePaths::new(ui.instance_path("Required")).content_manifest())
|
||||
.unwrap();
|
||||
ui.app.mods_state.entries = vec![content_entry("Library", library_path.clone())];
|
||||
ui.app.mods_state.list_state.selected = Some(0);
|
||||
ui.app.focused = FocusedArea::Content;
|
||||
ui.app.content_tab = ContentTab::Mods;
|
||||
|
||||
ui.key(KeyCode::Char('d'));
|
||||
|
||||
assert!(matches!(
|
||||
confirm::pending_target(),
|
||||
Some(confirm::ConfirmTarget::Content { dependents, .. })
|
||||
if dependents == vec!["root"]
|
||||
));
|
||||
ui.key(KeyCode::Enter);
|
||||
assert!(!Path::new(&library_path).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_account_delete_updates_the_account_panel() {
|
||||
let mut ui = UiHarness::new();
|
||||
@@ -278,6 +427,9 @@ fn provider_conflict_selection_is_persisted() {
|
||||
resolution: crate::instance::Resolution::Ambiguous {
|
||||
candidates: candidates.clone(),
|
||||
},
|
||||
provider_aliases: Vec::new(),
|
||||
required_dependencies: Vec::new(),
|
||||
automatic_dependency: false,
|
||||
}],
|
||||
};
|
||||
let manifest_path =
|
||||
|
||||
@@ -36,6 +36,21 @@ fn instance_delete_confirmation_renders_the_complete_frame() {
|
||||
insta::assert_snapshot!(ui.screen());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orphan_dependency_confirmation_wraps_its_complete_message() {
|
||||
let mut ui = UiHarness::new();
|
||||
crate::tui::widgets::popups::confirm::set_pending_orphan_dependencies(vec![
|
||||
"mods/sodium-fabric-0.9.1+mc26.2.jar".into(),
|
||||
]);
|
||||
ui.app.focused = crate::tui::app::FocusedArea::ConfirmDelete;
|
||||
|
||||
ui.draw();
|
||||
|
||||
let screen = ui.screen();
|
||||
assert!(screen.contains("longer required"));
|
||||
assert!(screen.contains("sodium-fabric-0.9.1+mc26.2.jar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_conflict_renders_the_complete_frame() {
|
||||
let mut ui = UiHarness::new();
|
||||
|
||||
@@ -52,6 +52,8 @@ fn version(id: &str) -> VersionInfo {
|
||||
version_number: id.to_owned(),
|
||||
game_versions: vec!["1.21.1".to_owned()],
|
||||
loaders: vec!["fabric".to_owned()],
|
||||
version_type: crate::net::modrinth::VersionType::Release,
|
||||
dependencies: Vec::new(),
|
||||
date_published: "2026-01-02T12:00:00Z".to_owned(),
|
||||
files: Vec::new(),
|
||||
}
|
||||
@@ -478,6 +480,64 @@ fn confirmation_can_return_to_version_selection() {
|
||||
assert!(state.version_popup.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dependency_resolution_opens_the_existing_confirmation() {
|
||||
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(ContentKind::Mod);
|
||||
state.list.entries.push(project_entry(project, None));
|
||||
state.list.list_state.selected = Some(0);
|
||||
let versions = state.begin_versions().unwrap();
|
||||
DiscoveryState::push_action_result(
|
||||
&versions.pending,
|
||||
DiscoveryActionResult::Versions {
|
||||
request_id: versions.request_id,
|
||||
project_id: versions.project_id,
|
||||
result: Ok(vec![version("1.0.0")]),
|
||||
},
|
||||
);
|
||||
state.drain_pending();
|
||||
let request = state.begin_dependency_resolution().unwrap();
|
||||
assert!(state.version_popup.as_ref().unwrap().loading);
|
||||
let root_version = request.root.version.clone();
|
||||
DiscoveryState::push_action_result(
|
||||
&request.pending,
|
||||
DiscoveryActionResult::Dependencies {
|
||||
request_id: request.request_id,
|
||||
project_id: request.project_id,
|
||||
result: Ok(crate::instance::content::dependencies::DependencyPlan {
|
||||
items: vec![crate::instance::content::dependencies::PlannedInstall {
|
||||
provider: "modrinth".to_owned(),
|
||||
project_id: "project".to_owned(),
|
||||
title: "Project".to_owned(),
|
||||
version: root_version,
|
||||
installed_path: None,
|
||||
provider_aliases: Vec::new(),
|
||||
required_dependencies: Vec::new(),
|
||||
automatic_dependency: false,
|
||||
replacement: false,
|
||||
}],
|
||||
optional_dependencies: 0,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
state.drain_pending();
|
||||
|
||||
let popup = state.version_popup.as_ref().unwrap();
|
||||
assert!(popup.confirming);
|
||||
assert!(!popup.loading);
|
||||
assert!(popup.dependency_plan.is_some());
|
||||
assert!(state.begin_install().unwrap().dependency_plan.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_delete_only_clears_the_matching_installed_badge() {
|
||||
let first_path = PathBuf::from("mods/first.jar");
|
||||
@@ -559,6 +619,7 @@ fn successful_install_marks_the_project_and_closes_the_popup() {
|
||||
path: PathBuf::from("mods/project.jar"),
|
||||
replaced: false,
|
||||
skipped: false,
|
||||
orphaned_dependencies: Vec::new(),
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -607,6 +668,9 @@ fn installed_labels_follow_exact_manifest_projects() {
|
||||
version_id: "version".to_owned(),
|
||||
},
|
||||
},
|
||||
provider_aliases: Vec::new(),
|
||||
required_dependencies: Vec::new(),
|
||||
automatic_dependency: false,
|
||||
});
|
||||
state.refresh_installed_manifest(&manifest, std::path::Path::new("first"));
|
||||
assert_eq!(
|
||||
|
||||
@@ -521,6 +521,9 @@ fn manifest_metadata_keeps_an_embedded_icon_renderer() {
|
||||
version_id: "version".to_owned(),
|
||||
},
|
||||
},
|
||||
provider_aliases: Vec::new(),
|
||||
required_dependencies: Vec::new(),
|
||||
automatic_dependency: false,
|
||||
});
|
||||
|
||||
state.apply_manifest(&manifest, &minecraft_dir, crate::instance::ContentKind::Mod);
|
||||
|
||||
@@ -37,6 +37,8 @@ fn discovery_version_rows_only_show_the_version_number() {
|
||||
version_number: "3.2.4-fabric-26.1".to_owned(),
|
||||
game_versions: vec![],
|
||||
loaders: vec![],
|
||||
version_type: crate::net::modrinth::VersionType::Release,
|
||||
dependencies: Vec::new(),
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
};
|
||||
@@ -46,8 +48,8 @@ fn discovery_version_rows_only_show_the_version_number() {
|
||||
|
||||
#[test]
|
||||
fn discovery_confirmation_popup_fits_its_summary() {
|
||||
assert_eq!(version_popup_height(false), VERSION_POPUP_HEIGHT);
|
||||
assert_eq!(version_popup_height(true), 6);
|
||||
assert_eq!(version_popup_height(false, None), VERSION_POPUP_HEIGHT);
|
||||
assert_eq!(version_popup_height(true, None), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -102,6 +102,8 @@ fn import_modpack_renders_version_step() {
|
||||
version_number: "1.0.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
loaders: vec!["fabric".into()],
|
||||
version_type: crate::net::modrinth::VersionType::Release,
|
||||
dependencies: Vec::new(),
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
},
|
||||
@@ -112,6 +114,8 @@ fn import_modpack_renders_version_step() {
|
||||
version_number: "0.9.0".into(),
|
||||
game_versions: vec!["1.20.1".into()],
|
||||
loaders: vec!["fabric".into()],
|
||||
version_type: crate::net::modrinth::VersionType::Release,
|
||||
dependencies: Vec::new(),
|
||||
date_published: String::new(),
|
||||
files: vec![],
|
||||
},
|
||||
|
||||
@@ -108,6 +108,8 @@ fn discovered_modpack_version_skips_content_install_confirmation() {
|
||||
version_number: "1.0".to_owned(),
|
||||
game_versions: vec!["1.21.1".to_owned()],
|
||||
loaders: vec!["fabric".to_owned()],
|
||||
version_type: crate::net::modrinth::VersionType::Release,
|
||||
dependencies: Vec::new(),
|
||||
date_published: String::new(),
|
||||
files: Vec::new(),
|
||||
}]),
|
||||
|
||||
@@ -15,6 +15,7 @@ fn keybind_wrapping_uses_terminal_width_for_unicode_keys() {
|
||||
fn word_wrap_size_uses_terminal_width_for_unicode_text() {
|
||||
assert_eq!(word_wrap_size("Übergröße", 20), (9, 1));
|
||||
assert_eq!(word_wrap_size("世界 test", 6), (4, 2));
|
||||
assert_eq!(word_wrap_size("one\n\ntwo", 20), (3, 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -95,8 +95,10 @@ pub struct VersionPopupState {
|
||||
pub versions: Vec<VersionInfo>,
|
||||
pub selected: usize,
|
||||
pub loading: bool,
|
||||
pub resolving_dependencies: bool,
|
||||
pub confirming: bool,
|
||||
pub installing: bool,
|
||||
pub dependency_plan: Option<crate::instance::content::dependencies::DependencyPlan>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
@@ -177,6 +179,14 @@ pub struct InstallRequest {
|
||||
pub provider: String,
|
||||
pub version: VersionInfo,
|
||||
pub installed_path: Option<PathBuf>,
|
||||
pub dependency_plan: Option<crate::instance::content::dependencies::DependencyPlan>,
|
||||
pub pending: PendingActions,
|
||||
}
|
||||
|
||||
pub struct DependencyRequest {
|
||||
pub request_id: u64,
|
||||
pub project_id: String,
|
||||
pub root: crate::instance::content::dependencies::InstallRoot,
|
||||
pub pending: PendingActions,
|
||||
}
|
||||
|
||||
@@ -184,6 +194,7 @@ pub struct InstallCompletion {
|
||||
pub path: PathBuf,
|
||||
pub replaced: bool,
|
||||
pub skipped: bool,
|
||||
pub orphaned_dependencies: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
pub enum DiscoveryActionResult {
|
||||
@@ -203,6 +214,11 @@ pub enum DiscoveryActionResult {
|
||||
project_id: String,
|
||||
result: Result<Vec<VersionInfo>, String>,
|
||||
},
|
||||
Dependencies {
|
||||
request_id: u64,
|
||||
project_id: String,
|
||||
result: Result<crate::instance::content::dependencies::DependencyPlan, String>,
|
||||
},
|
||||
Install {
|
||||
request_id: u64,
|
||||
generation: u64,
|
||||
@@ -230,6 +246,7 @@ pub struct DiscoveryState {
|
||||
sources: std::collections::HashMap<String, Vec<crate::instance::ProviderProject>>,
|
||||
pub project_page: Option<ProjectPageState>,
|
||||
pub version_popup: Option<VersionPopupState>,
|
||||
pending_orphan_cleanup: Option<Vec<PathBuf>>,
|
||||
next_action_request_id: u64,
|
||||
stream: Option<ContentStream>,
|
||||
next_offset: usize,
|
||||
@@ -259,6 +276,7 @@ impl DiscoveryState {
|
||||
sources: std::collections::HashMap::new(),
|
||||
project_page: None,
|
||||
version_popup: None,
|
||||
pending_orphan_cleanup: None,
|
||||
next_action_request_id: 0,
|
||||
stream: None,
|
||||
next_offset: 0,
|
||||
@@ -421,8 +439,10 @@ impl DiscoveryState {
|
||||
versions: Vec::new(),
|
||||
selected: 0,
|
||||
loading: true,
|
||||
resolving_dependencies: false,
|
||||
confirming: false,
|
||||
installing: false,
|
||||
dependency_plan: None,
|
||||
error: None,
|
||||
});
|
||||
Some(VersionsRequest {
|
||||
@@ -451,7 +471,9 @@ impl DiscoveryState {
|
||||
popup.versions.clear();
|
||||
popup.selected = 0;
|
||||
popup.loading = true;
|
||||
popup.resolving_dependencies = false;
|
||||
popup.confirming = false;
|
||||
popup.dependency_plan = None;
|
||||
popup.error = None;
|
||||
Some(VersionsRequest {
|
||||
request_id: popup.request_id,
|
||||
@@ -616,6 +638,7 @@ impl DiscoveryState {
|
||||
provider: popup.provider.clone(),
|
||||
version,
|
||||
installed_path: popup.installed_path.clone(),
|
||||
dependency_plan: popup.dependency_plan.clone(),
|
||||
pending: self.pending_actions.clone(),
|
||||
};
|
||||
self.version_popup = None;
|
||||
@@ -638,6 +661,33 @@ impl DiscoveryState {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn begin_dependency_resolution(&mut self) -> Option<DependencyRequest> {
|
||||
let popup = self.version_popup.as_mut()?;
|
||||
if popup.loading
|
||||
|| popup.installing
|
||||
|| popup.selecting_minecraft_version
|
||||
|| popup.confirming
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let version = popup.selected_version()?.clone();
|
||||
popup.loading = true;
|
||||
popup.resolving_dependencies = true;
|
||||
popup.error = None;
|
||||
Some(DependencyRequest {
|
||||
request_id: popup.request_id,
|
||||
project_id: popup.project_id.clone(),
|
||||
root: crate::instance::content::dependencies::InstallRoot {
|
||||
provider: popup.provider.clone(),
|
||||
project_id: popup.project_id.clone(),
|
||||
title: popup.project_title.clone(),
|
||||
version,
|
||||
installed_path: popup.installed_path.clone(),
|
||||
},
|
||||
pending: self.pending_actions.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn select_minecraft_version(&mut self) -> bool {
|
||||
let Some(popup) = self.version_popup.as_mut() else {
|
||||
return false;
|
||||
@@ -851,6 +901,27 @@ impl DiscoveryState {
|
||||
Err(error) => popup.error = Some(error),
|
||||
}
|
||||
}
|
||||
DiscoveryActionResult::Dependencies {
|
||||
request_id,
|
||||
project_id,
|
||||
result,
|
||||
} => {
|
||||
let Some(popup) = self.version_popup.as_mut().filter(|popup| {
|
||||
popup.request_id == request_id && popup.project_id == project_id
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
popup.loading = false;
|
||||
popup.resolving_dependencies = false;
|
||||
match result {
|
||||
Ok(plan) => {
|
||||
popup.dependency_plan = Some(plan);
|
||||
popup.confirming = true;
|
||||
popup.error = None;
|
||||
}
|
||||
Err(error) => popup.error = Some(error),
|
||||
}
|
||||
}
|
||||
DiscoveryActionResult::Install {
|
||||
request_id,
|
||||
generation,
|
||||
@@ -893,6 +964,9 @@ impl DiscoveryState {
|
||||
message: format!("{project_title}: {action}"),
|
||||
pushed_at: std::time::Instant::now(),
|
||||
});
|
||||
if !completion.orphaned_dependencies.is_empty() {
|
||||
self.pending_orphan_cleanup = Some(completion.orphaned_dependencies);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
crate::feedback::errors::push_error(crate::feedback::errors::ErrorEvent {
|
||||
@@ -915,6 +989,10 @@ impl DiscoveryState {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn take_orphan_cleanup(&mut self) -> Option<Vec<PathBuf>> {
|
||||
self.pending_orphan_cleanup.take()
|
||||
}
|
||||
|
||||
fn should_load_more(&self) -> bool {
|
||||
if self.page_loading
|
||||
|| self.exhausted
|
||||
|
||||
@@ -625,12 +625,14 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
let popup_area = area.centered(
|
||||
Constraint::Percentage(50),
|
||||
Constraint::Length(
|
||||
version_popup_height(popup.confirming).min(area.height.saturating_sub(2)),
|
||||
version_popup_height(popup.confirming, popup.dependency_plan.as_ref())
|
||||
.min(area.height.saturating_sub(2)),
|
||||
),
|
||||
);
|
||||
let theme = THEME.as_ref();
|
||||
let title = popup.title();
|
||||
let loading = popup.loading;
|
||||
let resolving_dependencies = popup.resolving_dependencies;
|
||||
let installing = popup.installing;
|
||||
let confirming = popup.confirming;
|
||||
let error = popup.error.clone();
|
||||
@@ -654,6 +656,31 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
.unwrap_or_else(|| "Unknown".to_owned());
|
||||
let replacing = popup.installed_path.is_some();
|
||||
let provider_label = popup.provider_label().to_owned();
|
||||
let dependency_installs = popup
|
||||
.dependency_plan
|
||||
.as_ref()
|
||||
.map(|plan| {
|
||||
plan.dependency_installs()
|
||||
.map(|item| item.title.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let dependency_replacements = popup
|
||||
.dependency_plan
|
||||
.as_ref()
|
||||
.map(|plan| {
|
||||
plan.dependency_replacements()
|
||||
.map(|item| format!("{} -> {}", item.title, item.version.version_number))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let optional_dependencies = popup
|
||||
.dependency_plan
|
||||
.as_ref()
|
||||
.map(|plan| plan.optional_dependencies)
|
||||
.unwrap_or_default();
|
||||
let can_switch_provider = popup.sources.len() > 1;
|
||||
let items = if selecting_minecraft_version {
|
||||
popup
|
||||
@@ -707,25 +734,37 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
.style(Style::default().fg(THEME.as_ref().text_dim()))
|
||||
.render(area, buffer);
|
||||
} else if loading {
|
||||
Paragraph::new("Loading compatible versions...")
|
||||
.style(Style::default().fg(THEME.as_ref().text_dim()))
|
||||
.render(area, buffer);
|
||||
Paragraph::new(if resolving_dependencies {
|
||||
"Resolving required dependencies..."
|
||||
} else {
|
||||
"Loading compatible versions..."
|
||||
})
|
||||
.style(Style::default().fg(THEME.as_ref().text_dim()))
|
||||
.render(area, buffer);
|
||||
} else if let Some(error) = &error {
|
||||
Paragraph::new(error.as_str())
|
||||
.style(Style::default().fg(THEME.as_ref().error()))
|
||||
.wrap(Wrap { trim: true })
|
||||
.render(area, buffer);
|
||||
} else if confirming {
|
||||
crate::tui::widgets::popups::base::render_summary(
|
||||
&[
|
||||
("Version", selected_version.as_str()),
|
||||
("Minecraft", minecraft_versions.as_str()),
|
||||
("Loader", loaders.as_str()),
|
||||
("Released", release_date.as_str()),
|
||||
],
|
||||
area,
|
||||
buffer,
|
||||
);
|
||||
let mut rows = vec![
|
||||
("Version", selected_version.as_str()),
|
||||
("Minecraft", minecraft_versions.as_str()),
|
||||
("Loader", loaders.as_str()),
|
||||
("Released", release_date.as_str()),
|
||||
];
|
||||
if !dependency_installs.is_empty() {
|
||||
rows.push(("Also installs", dependency_installs.as_str()));
|
||||
}
|
||||
if !dependency_replacements.is_empty() {
|
||||
rows.push(("Also changes", dependency_replacements.as_str()));
|
||||
}
|
||||
let optional_text;
|
||||
if optional_dependencies > 0 {
|
||||
optional_text = optional_dependencies.to_string();
|
||||
rows.push(("Optional not installed", optional_text.as_str()));
|
||||
}
|
||||
crate::tui::widgets::popups::base::render_summary(&rows, area, buffer);
|
||||
} else if items.is_empty() {
|
||||
Paragraph::new(if selecting_minecraft_version {
|
||||
"No compatible Minecraft versions found."
|
||||
@@ -747,8 +786,19 @@ fn render_version_popup(frame: &mut Frame, area: Rect, state: &DiscoveryState) {
|
||||
frame.render_widget(popup, popup_area);
|
||||
}
|
||||
|
||||
fn version_popup_height(confirming: bool) -> u16 {
|
||||
if confirming { 6 } else { VERSION_POPUP_HEIGHT }
|
||||
fn version_popup_height(
|
||||
confirming: bool,
|
||||
plan: Option<&crate::instance::content::dependencies::DependencyPlan>,
|
||||
) -> u16 {
|
||||
if !confirming {
|
||||
return VERSION_POPUP_HEIGHT;
|
||||
}
|
||||
let Some(plan) = plan else {
|
||||
return 6;
|
||||
};
|
||||
6 + u16::from(plan.dependency_installs().next().is_some())
|
||||
+ u16::from(plan.dependency_replacements().next().is_some())
|
||||
+ u16::from(plan.optional_dependencies > 0)
|
||||
}
|
||||
|
||||
fn confirmation_values(values: &[String]) -> String {
|
||||
|
||||
@@ -9,7 +9,7 @@ use ratatui::{
|
||||
layout::Rect,
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Paragraph, Widget},
|
||||
widgets::{Paragraph, Widget, Wrap},
|
||||
};
|
||||
|
||||
use crate::config::theme::THEME;
|
||||
@@ -37,22 +37,58 @@ pub enum ConfirmTarget {
|
||||
Content {
|
||||
name: String,
|
||||
path: std::path::PathBuf,
|
||||
dependents: Vec<String>,
|
||||
},
|
||||
OrphanDependencies {
|
||||
paths: Vec<std::path::PathBuf>,
|
||||
},
|
||||
}
|
||||
|
||||
impl ConfirmTarget {
|
||||
fn title(&self) -> String {
|
||||
format!(" Delete '{}' ", self.name())
|
||||
match self {
|
||||
Self::OrphanDependencies { .. } => " Remove unused libraries ".to_owned(),
|
||||
_ => format!(" Delete '{}' ", self.name()),
|
||||
}
|
||||
}
|
||||
|
||||
fn body(&self) -> &'static str {
|
||||
fn body(&self) -> String {
|
||||
match self {
|
||||
ConfirmTarget::Instance { .. } => "This will permanently remove the instance",
|
||||
ConfirmTarget::Account { .. } => "This will permanently remove this account",
|
||||
ConfirmTarget::ConfigProfile { .. } => {
|
||||
"This will permanently remove this config profile"
|
||||
ConfirmTarget::Instance { .. } => {
|
||||
"This will permanently remove the instance".to_owned()
|
||||
}
|
||||
ConfirmTarget::Account { .. } => "This will permanently remove this account".to_owned(),
|
||||
ConfirmTarget::ConfigProfile { .. } => {
|
||||
"This will permanently remove this config profile".to_owned()
|
||||
}
|
||||
ConfirmTarget::Content { dependents, .. } if !dependents.is_empty() => {
|
||||
format!(
|
||||
"This library is still required by:\n{}\n\nDeleting it may break those mods.",
|
||||
dependents
|
||||
.iter()
|
||||
.map(|name| format!("- {name}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
)
|
||||
}
|
||||
ConfirmTarget::Content { .. } => {
|
||||
"This will permanently remove the selected item".to_owned()
|
||||
}
|
||||
ConfirmTarget::OrphanDependencies { paths } => {
|
||||
format!(
|
||||
"These automatically installed libraries are no longer required:\n{}",
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| format!(
|
||||
"- {}",
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.unwrap_or("library")
|
||||
))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
)
|
||||
}
|
||||
ConfirmTarget::Content { .. } => "This will permanently remove the selected item",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +98,15 @@ impl ConfirmTarget {
|
||||
ConfirmTarget::Account { username, .. } => username,
|
||||
ConfirmTarget::ConfigProfile { profile } => profile,
|
||||
ConfirmTarget::Content { name, .. } => name,
|
||||
ConfirmTarget::OrphanDependencies { .. } => "unused libraries",
|
||||
}
|
||||
}
|
||||
|
||||
fn confirm_label(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Content { dependents, .. } if !dependents.is_empty() => " delete anyway",
|
||||
Self::OrphanDependencies { .. } => " remove all",
|
||||
_ => " confirm",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,12 +131,25 @@ pub fn set_pending_instance_delete(name: impl Into<String>) {
|
||||
}
|
||||
|
||||
pub fn set_pending_content_delete(name: impl Into<String>, path: impl Into<std::path::PathBuf>) {
|
||||
set_pending_managed_content_delete(name, path, Vec::new());
|
||||
}
|
||||
|
||||
pub fn set_pending_managed_content_delete(
|
||||
name: impl Into<String>,
|
||||
path: impl Into<std::path::PathBuf>,
|
||||
dependents: Vec<String>,
|
||||
) {
|
||||
set_pending(ConfirmTarget::Content {
|
||||
name: name.into(),
|
||||
path: path.into(),
|
||||
dependents,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn set_pending_orphan_dependencies(paths: Vec<std::path::PathBuf>) {
|
||||
set_pending(ConfirmTarget::OrphanDependencies { paths });
|
||||
}
|
||||
|
||||
pub fn pending_target() -> Option<ConfirmTarget> {
|
||||
match CONFIRM_STATE.lock() {
|
||||
Ok(s) => s.target.clone(),
|
||||
@@ -112,19 +170,25 @@ pub fn clear_pending() {
|
||||
|
||||
pub struct ConfirmPopup {
|
||||
title: String,
|
||||
body: &'static str,
|
||||
body: String,
|
||||
confirm_label: &'static str,
|
||||
}
|
||||
|
||||
impl ConfirmPopup {
|
||||
pub fn new(title: impl Into<String>, body: &'static str) -> Self {
|
||||
pub fn new(
|
||||
title: impl Into<String>,
|
||||
body: impl Into<String>,
|
||||
confirm_label: &'static str,
|
||||
) -> Self {
|
||||
Self {
|
||||
title: title.into(),
|
||||
body,
|
||||
body: body.into(),
|
||||
confirm_label,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_target(target: &ConfirmTarget) -> Self {
|
||||
Self::new(target.title(), target.body())
|
||||
Self::new(target.title(), target.body(), target.confirm_label())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,11 +203,12 @@ impl Widget for ConfirmPopup {
|
||||
.fg(theme.text_dim())
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)]);
|
||||
let kb = keybind_line(&[("Enter", " confirm")]);
|
||||
let kb = keybind_line(&[("Enter", self.confirm_label)]);
|
||||
|
||||
let border_color = theme.text_dim();
|
||||
let bg_color = theme.surface();
|
||||
let text_color = theme.text();
|
||||
let body = self.body;
|
||||
let popup = PopupFrame {
|
||||
title,
|
||||
border_color,
|
||||
@@ -151,8 +216,9 @@ impl Widget for ConfirmPopup {
|
||||
keybinds: Some(kb),
|
||||
search_line: None,
|
||||
content: Box::new(move |inner, buf| {
|
||||
Paragraph::new(self.body)
|
||||
Paragraph::new(body.as_str())
|
||||
.style(Style::default().fg(text_color))
|
||||
.wrap(Wrap { trim: true })
|
||||
.render(inner, buf);
|
||||
}),
|
||||
};
|
||||
@@ -165,10 +231,11 @@ pub fn confirm_popup_area(frame_area: Rect, target: &ConfirmTarget) -> Rect {
|
||||
use super::word_wrap_size;
|
||||
use ratatui::layout::Constraint;
|
||||
const MAX_W: usize = 48;
|
||||
let body = target.body();
|
||||
let title_w = Span::raw(target.name()).width() + 12;
|
||||
let (body_w, _) = word_wrap_size(target.body(), MAX_W);
|
||||
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(target.body(), inner_w);
|
||||
let (_, lines) = word_wrap_size(&body, inner_w);
|
||||
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))
|
||||
|
||||
@@ -42,23 +42,25 @@ pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) {
|
||||
return (0, 1);
|
||||
}
|
||||
|
||||
let mut lines: usize = 1;
|
||||
let mut current_line_len: usize = 0;
|
||||
let mut widest_line: usize = 0;
|
||||
|
||||
for word in text.split_whitespace() {
|
||||
let word_len = Span::raw(word).width().min(max_inner_width);
|
||||
if current_line_len == 0 {
|
||||
current_line_len = word_len;
|
||||
} else if current_line_len + 1 + word_len <= max_inner_width {
|
||||
current_line_len += 1 + word_len;
|
||||
} else {
|
||||
widest_line = widest_line.max(current_line_len);
|
||||
lines += 1;
|
||||
current_line_len = word_len;
|
||||
let mut lines = 0;
|
||||
for logical_line in text.split('\n') {
|
||||
let mut current_line_len = 0;
|
||||
lines += 1;
|
||||
for word in logical_line.split_whitespace() {
|
||||
let word_len = Span::raw(word).width().min(max_inner_width);
|
||||
if current_line_len == 0 {
|
||||
current_line_len = word_len;
|
||||
} else if current_line_len + 1 + word_len <= max_inner_width {
|
||||
current_line_len += 1 + word_len;
|
||||
} else {
|
||||
widest_line = widest_line.max(current_line_len);
|
||||
lines += 1;
|
||||
current_line_len = word_len;
|
||||
}
|
||||
}
|
||||
widest_line = widest_line.max(current_line_len);
|
||||
}
|
||||
widest_line = widest_line.max(current_line_len);
|
||||
|
||||
(widest_line, lines)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user