use iced::{
Alignment, Element, Length, Padding,
widget::{Space, button, column, container, row, scrollable, text, text_input},
};
use knotra_ui::widget::{icon, record_row};
use knotra_vcs::model::operation::{OperationLog, OperationResult, ProjectOperationOutcome};
use crate::{
message::{HistoryMessage, Message},
state::AppState,
};
const TOOLBAR_MAX_WIDTH: f32 = 680.0;
pub fn view(state: &AppState) -> Element<'_, Message> {
let header = view_header(state);
let toolbar = view_toolbar(state);
let body = view_body(state);
column![header, toolbar, scrollable(body).height(Length::Fill)]
.height(Length::Fill)
.into()
}
fn view_header(state: &AppState) -> Element<'_, Message> {
row![text(state.t("history.title")).size(20)]
.spacing(12)
.align_y(Alignment::Center)
.padding(Padding::new(12.0))
.into()
}
fn view_toolbar(state: &AppState) -> Element<'_, Message> {
let input = text_input(state.t("history.search_hint"), &state.history_search)
.on_input(|s| Message::History(HistoryMessage::SearchChanged(s)))
.width(Length::Fill);
container(input)
.width(Length::Fill)
.max_width(TOOLBAR_MAX_WIDTH)
.padding(Padding {
top: 0.0,
bottom: 8.0,
left: 12.0,
right: 12.0,
})
.into()
}
fn view_body(state: &AppState) -> Element<'_, Message> {
if state.history_directory_unreadable {
return empty_state(state.t("history.directory_unreadable"));
}
if state.operation_logs.is_empty() {
return if state.history_unreadable_count > 0 {
empty_state(unreadable_count_message(state))
} else {
empty_state(state.t("history.empty"))
};
}
let q = state.history_search.to_lowercase();
let mut entries: Vec<Element<'_, Message>> = state
.operation_logs
.iter()
.filter(|log| {
q.is_empty()
|| super::operation_kind_label(state, &log.result.kind)
.to_lowercase()
.contains(&q)
|| log.result.per_project.iter().any(|p| {
p.project_id.to_string().contains(&q)
|| p.stdout.to_lowercase().contains(&q)
|| p.stderr.to_lowercase().contains(&q)
})
})
.map(|log| view_log_entry(state, log))
.collect();
if entries.is_empty() {
return empty_state(state.t("history.no_match"));
}
if state.history_unreadable_count > 0 {
entries.insert(0, text(unreadable_count_message(state)).size(12).into());
}
column(entries).spacing(6).padding(12).into()
}
fn unreadable_count_message(state: &AppState) -> String {
format!(
"{} {}",
state.t("history.unreadable_count_label"),
state.history_unreadable_count
)
}
fn empty_state(message: impl Into<String>) -> Element<'static, Message> {
container(text(message.into()).size(14))
.width(Length::Fill)
.padding(24)
.into()
}
fn view_log_entry<'a>(state: &'a AppState, log: &'a OperationLog) -> Element<'a, Message> {
let result = &log.result;
let expanded = state.history_expanded.contains(&result.operation_id);
let status = summarise_status(result);
let status_label = format!("{} {}", status.glyph, state.t(status.label_key));
let timestamp = result
.started_at
.format("%Y-%m-%d %H:%M:%S UTC")
.to_string();
let project_count = result.per_project.len();
let toggle_label = if expanded {
state.t("plain.hide_details")
} else {
state.t("plain.show_details")
};
let chevron = if expanded {
icon::chevron_down()
} else {
icon::chevron_right()
};
let op_id_toggle = result.operation_id.clone();
let primary_row = row![
text(super::operation_kind_label(state, &result.kind)).size(13),
Space::new().width(Length::Fill),
text(status_label).size(12),
button(
row![text(toggle_label).size(11), icon::icon_element(&chevron)]
.spacing(4)
.align_y(Alignment::Center)
)
.on_press(Message::History(HistoryMessage::EntryToggled(op_id_toggle))),
button(text(state.t("history.copy_log")).size(11))
.on_press(Message::CopyToClipboard(export_text(result))),
]
.spacing(8)
.align_y(Alignment::Center);
let secondary_row = row![
text(timestamp).size(11),
text(format!(
"{} {}",
state.t("history.project_count_label"),
project_count
))
.size(11),
]
.spacing(12);
let summary = column![primary_row, secondary_row].spacing(2);
let detail = expanded.then(|| view_log_detail(state, log));
record_row(summary.into(), detail)
}
fn view_log_detail<'a>(state: &'a AppState, log: &'a OperationLog) -> Element<'a, Message> {
let result = &log.result;
let mut rows: Vec<Element<'a, Message>> = Vec::new();
if result.rollback_attempted {
let rb_text = format!(
"{} {}",
state.t("history.rollback_note"),
if result.rollback_succeeded == Some(true) {
state.t("plain.activity.succeeded")
} else {
state.t("plain.activity.failed")
}
);
rows.push(text(rb_text).size(11).into());
}
for pr in &result.per_project {
let icon = match pr.effective_outcome() {
ProjectOperationOutcome::Succeeded => "✓",
ProjectOperationOutcome::Failed => "✗",
ProjectOperationOutcome::Skipped => "-",
};
rows.push(text(format!(" {icon} {}", pr.project_id)).size(12).into());
if let Some(reason) = &pr.skip_reason {
rows.push(
text(format!(" {}", super::skip_reason_display(state, reason)))
.size(10)
.into(),
);
}
if !pr.commands_executed.is_empty() {
rows.push(text(state.t("history.commands_header")).size(10).into());
for cmd in &pr.commands_executed {
rows.push(text(format!(" $ {cmd}")).size(10).into());
}
}
if pr.is_failed() && !pr.stderr.is_empty() {
let preview: String = pr.stderr.lines().take(3).collect::<Vec<_>>().join("\n");
rows.push(text(format!(" {preview}")).size(10).into());
}
}
if !log.recovery_hints.is_empty() {
rows.push(text(state.t("history.recovery_header")).size(11).into());
for hint in &log.recovery_hints {
rows.push(text(format!(" {}", hint.situation)).size(11).into());
for cmd in &hint.suggested_commands {
rows.push(text(format!(" $ {cmd}")).size(10).into());
}
}
}
column(rows).spacing(2).padding([4, 12]).into()
}
fn export_text(result: &OperationResult) -> String {
let kind = result.kind.to_string();
let ts = result
.started_at
.format("%Y-%m-%d %H:%M:%S UTC")
.to_string();
let status = summarise_status(result);
let status_text = format!("{} {}", status.glyph, status.label_en);
let mut text_parts = vec![format!("# {} — {} — {}", kind, ts, status_text)];
for pr in &result.per_project {
let ok = match pr.effective_outcome() {
ProjectOperationOutcome::Succeeded => "ok",
ProjectOperationOutcome::Failed => "FAILED",
ProjectOperationOutcome::Skipped => "SKIPPED",
};
text_parts.push(format!(" {} [{}]", pr.project_id, ok));
if let Some(reason) = &pr.skip_reason {
text_parts.push(format!(" {}", reason));
}
for cmd in &pr.commands_executed {
text_parts.push(format!(" $ {}", cmd));
}
if !pr.stderr.is_empty() {
for line in pr.stderr.lines().take(5) {
text_parts.push(format!(" {}", line));
}
}
}
text_parts.join("\n")
}
struct StatusSummary {
glyph: &'static str,
label_key: &'static str,
label_en: &'static str,
}
fn summarise_status(result: &OperationResult) -> StatusSummary {
let succeeded = result.successful_projects().len();
let failed = result.failed_projects().len();
let skipped = result.skipped_projects().len();
if result.rollback_attempted {
if result.rollback_succeeded == Some(true) {
StatusSummary {
glyph: "↩",
label_key: "history.rollback_note",
label_en: "Rolled back",
}
} else {
StatusSummary {
glyph: "✗",
label_key: "history.status_rollback_failed",
label_en: "Rollback failed",
}
}
} else if succeeded > 0 && failed == 0 && skipped == 0 {
StatusSummary {
glyph: "✓",
label_key: "history.status_success",
label_en: "Success",
}
} else if failed > 0 && (succeeded > 0 || skipped > 0) {
StatusSummary {
glyph: "⚠",
label_key: "history.status_partial",
label_en: "Partial",
}
} else if skipped > 0 && failed == 0 {
StatusSummary {
glyph: "-",
label_key: "history.status_skipped",
label_en: "Skipped",
}
} else {
StatusSummary {
glyph: "✗",
label_key: "history.status_failed",
label_en: "Failed",
}
}
}
#[cfg(test)]
mod tests {
use knotra_vcs::model::{
operation::{OperationId, OperationKind, ProjectOperationResult},
project::ProjectId,
};
use super::*;
fn sample_result(
per_project: Vec<ProjectOperationResult>,
rollback_attempted: bool,
rollback_succeeded: Option<bool>,
) -> OperationResult {
let now = chrono::Utc::now();
OperationResult {
operation_id: OperationId::new(),
kind: OperationKind::Fetch,
started_at: now,
finished_at: now,
per_project,
rollback_attempted,
rollback_succeeded,
}
}
fn succeeded_project(id: ProjectId) -> ProjectOperationResult {
ProjectOperationResult {
project_id: id,
outcome: ProjectOperationOutcome::Succeeded,
success: true,
skip_reason: None,
commands_executed: vec!["git fetch".to_owned()],
stdout: String::new(),
stderr: String::new(),
exit_code: Some(0),
error_message: None,
}
}
fn failed_project(id: ProjectId) -> ProjectOperationResult {
ProjectOperationResult {
project_id: id,
outcome: ProjectOperationOutcome::Failed,
success: false,
skip_reason: None,
commands_executed: Vec::new(),
stdout: String::new(),
stderr: String::new(),
exit_code: Some(1),
error_message: None,
}
}
fn skipped_project(id: ProjectId, skip_reason: Option<String>) -> ProjectOperationResult {
ProjectOperationResult {
project_id: id,
outcome: ProjectOperationOutcome::Skipped,
success: true,
skip_reason,
commands_executed: Vec::new(),
stdout: String::new(),
stderr: String::new(),
exit_code: None,
error_message: None,
}
}
#[test]
fn export_text_reports_a_successful_entry_in_english() {
let id = ProjectId::new();
let result = sample_result(vec![succeeded_project(id.clone())], false, None);
let text = export_text(&result);
assert!(
text.starts_with("# Fetch — "),
"expected an English kind label, got: {text}"
);
assert!(
text.contains("✓ Success"),
"expected the fixed English status label, got: {text}"
);
assert!(
text.contains(&format!("{id} [ok]")),
"expected the project id with its outcome tag, got: {text}"
);
assert!(
text.contains("$ git fetch"),
"expected the executed command, got: {text}"
);
}
#[test]
fn export_text_emits_the_skip_reason_code_verbatim() {
let id = ProjectId::new();
let skipped = skipped_project(id, Some("retry:not_in_active_workspace".to_owned()));
let result = sample_result(vec![skipped], false, None);
let text = export_text(&result);
assert!(
text.contains("retry:not_in_active_workspace"),
"expected the raw code, untranslated, got: {text}"
);
}
#[test]
fn export_text_includes_stderr_lines() {
let id = ProjectId::new();
let failed = ProjectOperationResult {
project_id: id,
outcome: ProjectOperationOutcome::Failed,
success: false,
skip_reason: None,
commands_executed: Vec::new(),
stdout: String::new(),
stderr: "fatal: could not read remote\nauthentication failed".to_owned(),
exit_code: Some(1),
error_message: Some("fatal: could not read remote".to_owned()),
};
let result = sample_result(vec![failed], false, None);
let text = export_text(&result);
assert!(
text.contains("fatal: could not read remote"),
"expected the first stderr line, got: {text}"
);
assert!(
text.contains("authentication failed"),
"expected the second stderr line, got: {text}"
);
assert!(
text.contains("[FAILED]"),
"expected the failed outcome tag, got: {text}"
);
}
#[test]
fn label_en_matches_the_english_catalog_for_every_status_arm() {
let en = knotra_ui::i18n::Catalog::for_locale(knotra_ui::i18n::Locale::En);
let id = ProjectId::new();
let cases: Vec<(&str, OperationResult, &str)> = vec![
(
"rolled back",
sample_result(vec![succeeded_project(id.clone())], true, Some(true)),
"history.rollback_note",
),
(
"rollback failed",
sample_result(vec![succeeded_project(id.clone())], true, Some(false)),
"history.status_rollback_failed",
),
(
"success",
sample_result(vec![succeeded_project(id.clone())], false, None),
"history.status_success",
),
(
"partial",
sample_result(
vec![succeeded_project(id.clone()), failed_project(id.clone())],
false,
None,
),
"history.status_partial",
),
(
"skipped",
sample_result(vec![skipped_project(id.clone(), None)], false, None),
"history.status_skipped",
),
(
"failed",
sample_result(vec![failed_project(id.clone())], false, None),
"history.status_failed",
),
];
for (case, result, expected_key) in cases {
let summary = summarise_status(&result);
assert_eq!(
summary.label_key, expected_key,
"the `{case}` fixture no longer reaches the `{expected_key}` arm of \
summarise_status — it landed on `{}` instead",
summary.label_key
);
assert_eq!(
summary.label_en,
en.t(summary.label_key),
"label_en drifted from the English catalog for the `{case}` status arm \
(label_key = `{}`)",
summary.label_key
);
}
}
}