use iced::{
Alignment, Element, Length,
widget::{Space, column, row, text},
};
use knotra_ui::widget::{
BUTTON_HEIGHT, FONT_BODY, FONT_SMALL, NoticeTone, Tokens, notice,
overlay::{OverlayWidth, surface},
reasoned, style,
};
use knotra_vcs::{ProjectId, VcsKind};
use crate::{
message::{ConflictOpsMessage, Message},
state::AppState,
};
pub fn resolve_panel<'a>(state: &'a AppState, project_id: &'a ProjectId) -> Element<'a, Message> {
let tokens = &state.theme.tokens;
let name = project_name_for(state, project_id);
let ops = &state.conflict_ops;
let vcs_kind = conflict_vcs_kind_for_project(state, project_id);
let git_actions_supported = vcs_kind == Some(VcsKind::Git);
let abort_supported = git_actions_supported && project_has_git_merge_state(state, project_id);
let editor_configured = state.config.external_editor.is_some();
let merge_tool_configured = state.config.external_merge_tool.is_some();
let close_msg = (!matches!(
ops.phase,
crate::state::conflict_ops::ConflictPhase::Operating { .. }
))
.then_some(Message::ConflictOps(ConflictOpsMessage::PanelClosed));
let content: Element<'_, Message> = match &ops.phase {
crate::state::conflict_ops::ConflictPhase::Loading(id) if id == project_id => {
text(state.t("plain.resolve.loading"))
.size(FONT_BODY)
.into()
}
crate::state::conflict_ops::ConflictPhase::Operating {
project_id: id,
action,
} if id == project_id => column![
text(action).size(FONT_BODY),
text(state.t("plain.resolve.working_hint")).size(FONT_SMALL),
]
.spacing(8)
.into(),
crate::state::conflict_ops::ConflictPhase::Done {
project_id: id,
success,
message,
result,
} if id == project_id => {
let tone = if *success {
NoticeTone::Success
} else {
NoticeTone::Danger
};
let banner = notice(tokens, tone, None, message.as_str(), None);
let details_label = if state.show_op_details {
state.t("plain.hide_details")
} else {
state.t("plain.show_details")
};
let mut result_col = column![
banner,
styled_button(
tokens,
details_label,
Some(Message::ToggleOpDetails),
style::ghost,
),
]
.spacing(8);
if state.show_op_details
&& let Some(result) = result
{
for command in &result.commands_executed {
result_col =
result_col.push(text(format!("command: {command}")).size(FONT_SMALL));
}
if !result.stdout.is_empty() {
result_col = result_col
.push(text(format!("stdout: {}", result.stdout)).size(FONT_SMALL));
}
if !result.stderr.is_empty() {
result_col = result_col
.push(text(format!("stderr: {}", result.stderr)).size(FONT_SMALL));
}
if let Some(error) = &result.error_message {
result_col = result_col.push(text(format!("error: {error}")).size(FONT_SMALL));
}
}
result_col.into()
}
_ => {
let detail = match &ops.phase {
crate::state::conflict_ops::ConflictPhase::Browsing {
project_id: id,
detail,
} if id == project_id => Some(detail),
_ => ops.cached.get(project_id),
};
if let Some(detail) = detail {
if detail.conflicted_files.is_empty() {
text(state.t("plain.resolve.no_files"))
.size(FONT_BODY)
.into()
} else {
let file_rows: Vec<Element<'_, Message>> = detail
.conflicted_files
.iter()
.map(|f| {
let editor_reason = (!editor_configured)
.then_some(state.t("plain.resolve.editor_not_configured"));
let open_editor_msg =
editor_configured.then_some(Message::ConflictOps(
ConflictOpsMessage::OpenInEditorRequested(f.path.clone()),
));
let merge_tool_reason = (!merge_tool_configured)
.then_some(state.t("plain.resolve.merge_tool_not_configured"));
let open_merge_tool_msg =
merge_tool_configured.then_some(Message::ConflictOps(
ConflictOpsMessage::OpenInMergeToolRequested(f.path.clone()),
));
let mut line1 = row![
text("!").size(FONT_BODY).width(Length::Fixed(22.0)),
text(&f.path).size(FONT_BODY).width(Length::Fill),
Space::new().width(Length::Fixed(8.0)),
reasoned(
tokens,
state.t("plain.resolve.open_editor"),
open_editor_msg,
editor_reason,
false,
style::secondary,
),
reasoned(
tokens,
state.t("plain.resolve.open_merge_tool"),
open_merge_tool_msg,
merge_tool_reason,
false,
style::secondary,
),
]
.align_y(Alignment::Center)
.spacing(6);
let mut file_col = column![].spacing(4);
match third_slot_for(state, tokens, vcs_kind, project_id, &f.path) {
ThirdSlot::Button(control) => {
line1 = line1.push(control);
file_col = file_col.push(line1);
}
ThirdSlot::Prose(sentence) => {
file_col = file_col.push(line1);
file_col = file_col.push(row![
Space::new().width(Length::Fixed(28.0)),
text(sentence).size(FONT_SMALL).width(Length::Fill),
]);
}
}
file_col.into()
})
.collect();
column(file_rows).spacing(8).into()
}
} else {
text(state.t("plain.resolve.loading"))
.size(FONT_BODY)
.into()
}
}
};
let stop_control: Element<'_, Message> = if abort_supported {
styled_button(
tokens,
state.t("plain.resolve.stop_attempt"),
Some(Message::ConflictOps(
ConflictOpsMessage::AbortMergeRequested(project_id.clone()),
)),
style::secondary,
)
} else {
Space::new().width(Length::Fixed(0.0)).into()
};
let footer = row![
stop_control,
Space::new().width(Length::Fill),
styled_button(
tokens,
state.t("action.close"),
close_msg.clone(),
style::ghost
),
]
.align_y(Alignment::Center);
let body = column![
text(state.t("plain.resolve.instruction")).size(FONT_BODY),
content,
]
.spacing(14);
surface(
tokens,
OverlayWidth::Large.resolve(state.window_width),
format!("{} — {}", state.t("plain.resolve.title"), name),
close_msg,
false,
body,
footer,
)
}
fn styled_button<'a>(
tokens: &Tokens,
label: &'a str,
on_press: Option<Message>,
style_fn: fn(&Tokens, iced::widget::button::Status) -> iced::widget::button::Style,
) -> Element<'a, Message> {
let t = tokens.clone();
iced::widget::button(text(label).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press_maybe(on_press)
.style(move |_theme, status| style::with_focus_ring(&t, false, style_fn(&t, status)))
.into()
}
enum ThirdSlot<'a> {
Button(Element<'a, Message>),
Prose(String),
}
fn third_slot_for<'a>(
state: &'a AppState,
tokens: &Tokens,
vcs_kind: Option<VcsKind>,
project_id: &ProjectId,
file_path: &str,
) -> ThirdSlot<'a> {
match vcs_kind {
Some(VcsKind::Git) => {
let t = tokens.clone();
ThirdSlot::Button(
iced::widget::button(
text(state.t("plain.resolve.mark_done")).size(FONT_SMALL + 1.0),
)
.height(36.0)
.padding([0, 10])
.on_press(Message::ConflictOps(
ConflictOpsMessage::MarkResolvedRequested {
project_id: project_id.clone(),
file_path: file_path.to_owned(),
},
))
.style(move |_theme, status| {
style::with_focus_ring(&t, false, style::secondary(&t, status))
})
.into(),
)
}
Some(VcsKind::Jujutsu) => ThirdSlot::Prose(jj_finish_hint(state, file_path)),
None => ThirdSlot::Prose(state.t("plain.resolve.unsupported").to_owned()),
}
}
fn conflict_vcs_kind_for_project(state: &AppState, project_id: &ProjectId) -> Option<VcsKind> {
state
.workspace_status
.as_ref()
.and_then(|ws| {
ws.projects
.iter()
.find(|status| &status.project_id == project_id)
})
.map(|status| status.identity.vcs_kind)
.or_else(|| {
state
.workspace
.as_ref()
.and_then(|ws| ws.projects.iter().find(|project| &project.id == project_id))
.and_then(|project| {
let path = std::path::Path::new(&project.path);
if path.join(".jj").is_dir() {
Some(VcsKind::Jujutsu)
} else if path.join(".git").exists() {
Some(VcsKind::Git)
} else {
None
}
})
})
}
fn jj_finish_hint(state: &AppState, file_path: &str) -> String {
format!(
"{} `jj resolve {file_path}`",
state.t("plain.resolve.jj_finish_hint")
)
}
fn project_has_git_merge_state(state: &AppState, project_id: &ProjectId) -> bool {
state
.workspace
.as_ref()
.and_then(|ws| ws.projects.iter().find(|project| &project.id == project_id))
.map(|project| {
let path = std::path::Path::new(&project.path);
path.join(".git").join("MERGE_HEAD").exists()
})
.unwrap_or(false)
}
fn project_name_for(state: &AppState, id: &ProjectId) -> String {
state
.workspace
.as_ref()
.and_then(|ws| ws.projects.iter().find(|p| &p.id == id))
.map(|p| p.name.clone())
.unwrap_or_else(|| id.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::AppConfig;
use knotra_vcs::{
ConflictStatus, RemoteStatus, RepositoryIdentity, WorkingTreeStatus, WorkspaceStatus,
};
fn status_for(project_id: ProjectId, vcs_kind: VcsKind) -> knotra_vcs::ProjectStatus {
knotra_vcs::ProjectStatus {
project_id,
identity: RepositoryIdentity {
path: "/tmp".into(),
vcs_kind,
},
context: None,
remote: RemoteStatus::default(),
working_tree: WorkingTreeStatus::default(),
conflict: ConflictStatus::default(),
refreshed_at: chrono::Utc::now(),
read_error: None,
}
}
fn state_with_status(vcs_kind: VcsKind) -> (AppState, ProjectId) {
let mut state = AppState::new(AppConfig::default());
let project_id = ProjectId::new();
state.workspace_status = Some(WorkspaceStatus {
projects: vec![status_for(project_id.clone(), vcs_kind)],
last_refresh: None,
});
(state, project_id)
}
#[test]
fn conflict_vcs_kind_for_project_reports_jujutsu_for_a_jj_project() {
let (state, project_id) = state_with_status(VcsKind::Jujutsu);
assert_eq!(
conflict_vcs_kind_for_project(&state, &project_id),
Some(VcsKind::Jujutsu)
);
}
#[test]
fn conflict_vcs_kind_for_project_reports_git_for_a_git_project() {
let (state, project_id) = state_with_status(VcsKind::Git);
assert_eq!(
conflict_vcs_kind_for_project(&state, &project_id),
Some(VcsKind::Git)
);
}
#[test]
fn conflict_vcs_kind_for_project_reports_none_with_neither_marker_present() {
let tmp = tempfile::TempDir::new().expect("tempdir");
let mut state = AppState::new(AppConfig::default());
let project = knotra_vcs::Project::new("svc", tmp.path().to_string_lossy());
let project_id = project.id.clone();
state.workspace = Some(knotra_vcs::Workspace {
projects: vec![project],
..knotra_vcs::Workspace::new("Test")
});
assert_eq!(conflict_vcs_kind_for_project(&state, &project_id), None);
}
#[test]
fn conflict_vcs_kind_for_project_reports_none_when_absent_from_both_sources() {
let state = AppState::new(AppConfig::default());
let project_id = ProjectId::new();
assert_eq!(conflict_vcs_kind_for_project(&state, &project_id), None);
}
#[test]
fn jj_finish_hint_names_the_command_with_the_files_path() {
let state = AppState::new(AppConfig::default());
let hint = jj_finish_hint(&state, "src/lib.rs");
assert_eq!(hint, "Finish with: `jj resolve src/lib.rs`");
}
#[test]
fn third_slot_is_a_button_for_git_and_prose_for_jujutsu_and_none() {
let state = AppState::new(AppConfig::default());
let tokens = &state.theme.tokens;
let project_id = ProjectId::new();
assert!(matches!(
third_slot_for(
&state,
tokens,
Some(VcsKind::Git),
&project_id,
"src/lib.rs"
),
ThirdSlot::Button(_)
));
assert!(matches!(
third_slot_for(
&state,
tokens,
Some(VcsKind::Jujutsu),
&project_id,
"src/lib.rs"
),
ThirdSlot::Prose(_)
));
assert!(matches!(
third_slot_for(&state, tokens, None, &project_id, "src/lib.rs"),
ThirdSlot::Prose(_)
));
}
}