use iced::{
Alignment, Element, Length, Padding,
widget::{Space, button, column, container, row, scrollable, text},
};
use knotra_ui::widget::{
SMALL_BUTTON_HEIGHT, Tokens, Tone, WIDE_CONTENT_WIDTH, body_badge_diameter,
centered_button_label, centered_button_row, icon, list, record_row, status_badge,
status_symbol, strong, style, styled_text_input,
};
use knotra_vcs::model::operation::{OperationLog, OperationResult, ProjectOperationOutcome};
use crate::{
message::{HistoryMessage, Message},
state::{AppState, dashboard::badge_for_operation_outcome},
view::dashboard::WidthMode,
};
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> {
let tokens = &state.theme.tokens;
row![strong(
text(state.t("history.title")).size(snora::design::style::text::heading_size(tokens))
)]
.spacing(12)
.align_y(Alignment::Center)
.padding(Padding::new(12.0))
.into()
}
fn view_toolbar(state: &AppState) -> Element<'_, Message> {
let tokens = state.theme.tokens.clone();
let input = styled_text_input(
&tokens,
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> {
let tokens = &state.theme.tokens;
if state.history_directory_unreadable {
return empty_state(tokens, state.t("history.directory_unreadable"));
}
if state.operation_logs.is_empty() {
return if state.history_unreadable_count > 0 {
empty_state(tokens, unreadable_count_message(state))
} else {
empty_state(tokens, state.t("history.empty"))
};
}
let q = state.history_search.to_lowercase();
let 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| {
project_name_matches_search(state, p, &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(tokens, state.t("history.no_match"));
}
let notice = (state.history_unreadable_count > 0).then(|| {
Element::from(
text(unreadable_count_message(state))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens)),
)
});
let mut list_body = column![].spacing(6).padding(12);
if let Some(notice) = notice {
list_body = list_body.push(notice);
}
let list_column = list_body.push(list(tokens, entries));
match state.width_mode {
WidthMode::Wide => container(list_column.width(Length::Fixed(WIDE_CONTENT_WIDTH)))
.align_left(Length::Fill)
.into(),
WidthMode::Compact | WidthMode::Standard => list_column.into(),
}
}
fn unreadable_count_message(state: &AppState) -> String {
format!(
"{} {}",
state.t("history.unreadable_count_label"),
state.history_unreadable_count
)
}
fn empty_state(tokens: &Tokens, message: impl Into<String>) -> Element<'static, Message> {
container(
text(message.into())
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens)),
)
.width(Length::Fill)
.padding(24)
.into()
}
fn view_log_entry<'a>(state: &'a AppState, log: &'a OperationLog) -> Element<'a, Message> {
let tokens = &state.theme.tokens;
let result = &log.result;
let expanded = state.history_expanded.contains(&result.operation_id);
let status = summarise_status(result);
let timestamp = result
.started_at
.strftime("%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![
strong(
text(super::operation_kind_label(state, &result.kind))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
),
Space::new().width(Length::Fill),
row![
status_badge(
tokens,
status.badge.0,
&status.badge.1,
body_badge_diameter(tokens)
),
text(state.t(status.label_key))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens)),
]
.spacing(6)
.align_y(Alignment::Center),
button(centered_button_row(
row![
text(toggle_label)
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens)),
icon::icon_element(&chevron)
]
.spacing(4)
))
.height(SMALL_BUTTON_HEIGHT)
.padding([0, 10])
.on_press(Message::History(HistoryMessage::EntryToggled(op_id_toggle)))
.style({
let t = tokens.clone();
move |_theme, status| style::with_focus_ring(&t, false, style::secondary(&t, status))
}),
button(centered_button_label(
text(state.t("history.copy_log"))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
))
.height(SMALL_BUTTON_HEIGHT)
.padding([0, 10])
.on_press(Message::CopyToClipboard(export_text(
result,
&copied_log_names(state, result)
)))
.style({
let t = tokens.clone();
move |_theme, status| style::with_focus_ring(&t, false, style::secondary(&t, status))
}),
]
.spacing(8)
.align_y(Alignment::Center);
let secondary_row = row![
text(timestamp)
.size(snora::design::style::text::body_small_size(tokens))
.line_height(snora::design::style::text::body_small_line_height(tokens)),
text(format!(
"{} {}",
state.t("history.project_count_label"),
project_count
))
.size(snora::design::style::text::body_small_size(tokens))
.line_height(snora::design::style::text::body_small_line_height(tokens)),
]
.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)
}
enum ProjectNameResolution {
Stored(String),
Current(String),
Removed,
}
fn resolve_project_name(
state: &AppState,
pr: &knotra_vcs::model::operation::ProjectOperationResult,
) -> ProjectNameResolution {
if let Some(name) = &pr.project_name {
ProjectNameResolution::Stored(name.clone())
} else if let Some(name) = state.find_project_name(&pr.project_id) {
ProjectNameResolution::Current(name)
} else {
ProjectNameResolution::Removed
}
}
fn project_name_matches_search(
state: &AppState,
pr: &knotra_vcs::model::operation::ProjectOperationResult,
q: &str,
) -> bool {
let stored_matches = pr
.project_name
.as_deref()
.is_some_and(|name| name.to_lowercase().contains(q));
let current_matches = state
.find_project_name(&pr.project_id)
.is_some_and(|name| name.to_lowercase().contains(q));
stored_matches || current_matches
}
fn detail_project_name(
state: &AppState,
pr: &knotra_vcs::model::operation::ProjectOperationResult,
) -> String {
match resolve_project_name(state, pr) {
ProjectNameResolution::Stored(name) | ProjectNameResolution::Current(name) => name,
ProjectNameResolution::Removed => state.t("history.removed_project").to_owned(),
}
}
fn indented_stderr_preview(stderr: &str, take: usize) -> String {
stderr
.lines()
.take(take)
.map(|line| format!(" {line}"))
.collect::<Vec<_>>()
.join("\n")
}
fn view_log_detail<'a>(state: &'a AppState, log: &'a OperationLog) -> Element<'a, Message> {
let tokens = &state.theme.tokens;
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(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
}
for pr in &result.per_project {
let (tone, glyph) = badge_for_operation_outcome(pr.effective_outcome());
let name = detail_project_name(state, pr);
rows.push(
row![
status_badge(tokens, tone, &glyph, body_badge_diameter(tokens)),
text(name)
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens)),
]
.spacing(6)
.align_y(Alignment::Center)
.padding(Padding {
left: 14.0,
..Padding::ZERO
})
.into(),
);
if let Some(reason) = &pr.skip_reason {
rows.push(
text(format!(" {}", super::skip_reason_display(state, reason)))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
}
if !pr.commands_executed.is_empty() {
rows.push(
text(state.t("history.commands_header"))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
for cmd in &pr.commands_executed {
rows.push(
text(format!(" $ {cmd}"))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
}
}
if pr.is_failed() && !pr.stderr.is_empty() {
rows.push(
text(indented_stderr_preview(&pr.stderr, 3))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
}
}
if !log.recovery_hints.is_empty() {
rows.push(
text(state.t("history.recovery_header"))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
for hint in &log.recovery_hints {
rows.push(
text(format!(" {}", hint.situation))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
for cmd in &hint.suggested_commands {
rows.push(
text(format!(" $ {cmd}"))
.size(snora::design::style::text::body_size(tokens))
.line_height(snora::design::style::text::body_line_height(tokens))
.into(),
);
}
}
}
column(rows).spacing(2).padding([4, 12]).into()
}
fn copied_log_names(state: &AppState, result: &OperationResult) -> Vec<String> {
result
.per_project
.iter()
.map(|pr| match resolve_project_name(state, pr) {
ProjectNameResolution::Stored(name) | ProjectNameResolution::Current(name) => name,
ProjectNameResolution::Removed => "Removed project".to_owned(),
})
.collect()
}
fn export_text(result: &OperationResult, names: &[String]) -> String {
let kind = result.kind.to_string();
let ts = result
.started_at
.strftime("%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, name) in result.per_project.iter().zip(names) {
let ok = match pr.effective_outcome() {
ProjectOperationOutcome::Succeeded => "ok",
ProjectOperationOutcome::Failed => "FAILED",
ProjectOperationOutcome::Skipped => "SKIPPED",
};
text_parts.push(format!(" {name} ({}) [{}]", 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,
badge: (Tone, snora::Icon),
}
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",
badge: (Tone::Danger, status_symbol::alert()),
}
} else {
StatusSummary {
glyph: "✗",
label_key: "history.status_rollback_failed",
label_en: "Rollback failed",
badge: (Tone::Danger, status_symbol::alert()),
}
}
} else if succeeded > 0 && failed == 0 && skipped == 0 {
StatusSummary {
glyph: "✓",
label_key: "history.status_success",
label_en: "Success",
badge: (Tone::Success, status_symbol::all_set()),
}
} else if failed > 0 && (succeeded > 0 || skipped > 0) {
StatusSummary {
glyph: "⚠",
label_key: "history.status_partial",
label_en: "Partial",
badge: (Tone::Warning, status_symbol::alert()),
}
} else if skipped > 0 && failed == 0 {
StatusSummary {
glyph: "-",
label_key: "history.status_skipped",
label_en: "Skipped",
badge: (Tone::Info, status_symbol::skipped()),
}
} else {
StatusSummary {
glyph: "✗",
label_key: "history.status_failed",
label_en: "Failed",
badge: (Tone::Danger, status_symbol::alert()),
}
}
}
pub(crate) fn aggregate_badge(result: &OperationResult) -> (Tone, snora::Icon) {
summarise_status(result).badge
}
#[cfg(test)]
mod tests {
use knotra_vcs::model::{
operation::{OperationId, OperationKind, ProjectOperationResult},
project::ProjectId,
};
use knotra_vcs::{Project, Workspace};
use super::*;
#[test]
fn export_text_timestamp_format_is_stable() {
let mut result = sample_result(Vec::new(), false, None);
result.started_at = fixed_instant();
result.finished_at = result.started_at;
let text = export_text(&result, &[]);
assert!(
text.contains("2024-03-04 05:06:07 UTC"),
"expected the fixed instant formatted as \"2024-03-04 05:06:07 UTC\"; got: {text}"
);
}
#[test]
fn indented_stderr_preview_indents_every_line() {
let preview = indented_stderr_preview("error: failed to push\nhint: try fetch first", 3);
assert_eq!(
preview,
" error: failed to push\n hint: try fetch first"
);
}
#[test]
fn indented_stderr_preview_respects_take() {
let preview = indented_stderr_preview("one\ntwo\nthree\nfour", 2);
assert_eq!(preview, " one\n two");
}
fn fixed_instant() -> jiff::Timestamp {
jiff::Timestamp::from_second(1_709_528_767).unwrap()
}
fn sample_result(
per_project: Vec<ProjectOperationResult>,
rollback_attempted: bool,
rollback_succeeded: Option<bool>,
) -> OperationResult {
let now = jiff::Timestamp::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, name: &str) -> ProjectOperationResult {
ProjectOperationResult {
project_id: id,
project_name: Some(name.to_owned()),
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, name: &str) -> ProjectOperationResult {
ProjectOperationResult {
project_id: id,
project_name: Some(name.to_owned()),
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,
name: &str,
skip_reason: Option<String>,
) -> ProjectOperationResult {
ProjectOperationResult {
project_id: id,
project_name: Some(name.to_owned()),
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(), "dirty-1")], false, None);
let text = export_text(&result, &["dirty-1".to_owned()]);
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!("dirty-1 ({id}) [ok]")),
"expected the project's name, then its id in parens, then 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,
"clean-1",
Some("retry:not_in_active_workspace".to_owned()),
);
let result = sample_result(vec![skipped], false, None);
let text = export_text(&result, &["clean-1".to_owned()]);
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,
project_name: Some("ahead-1".to_owned()),
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, &["ahead-1".to_owned()]);
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(), "p")], true, Some(true)),
"history.rollback_note",
),
(
"rollback failed",
sample_result(vec![succeeded_project(id.clone(), "p")], true, Some(false)),
"history.status_rollback_failed",
),
(
"success",
sample_result(vec![succeeded_project(id.clone(), "p")], false, None),
"history.status_success",
),
(
"partial",
sample_result(
vec![
succeeded_project(id.clone(), "p"),
failed_project(id.clone(), "p"),
],
false,
None,
),
"history.status_partial",
),
(
"skipped",
sample_result(vec![skipped_project(id.clone(), "p", None)], false, None),
"history.status_skipped",
),
(
"failed",
sample_result(vec![failed_project(id.clone(), "p")], 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
);
}
}
fn state_with_registered_project(project: &Project) -> AppState {
let mut state = AppState::new(crate::config::AppConfig::default());
let mut workspace = Workspace::new("Demo");
workspace.projects.push(project.clone());
state.all_workspaces = vec![workspace];
state
}
fn result_with_name(
project_id: ProjectId,
project_name: Option<String>,
) -> ProjectOperationResult {
ProjectOperationResult {
project_id,
project_name,
outcome: ProjectOperationOutcome::Succeeded,
success: true,
skip_reason: None,
commands_executed: Vec::new(),
stdout: String::new(),
stderr: String::new(),
exit_code: Some(0),
error_message: None,
}
}
#[test]
fn resolve_project_name_covers_all_three_cases() {
let project = Project::new("current-name", "/tmp/p");
let state = state_with_registered_project(&project);
let stored = result_with_name(project.id.clone(), Some("name-as-logged".to_owned()));
assert!(matches!(
resolve_project_name(&state, &stored),
ProjectNameResolution::Stored(name) if name == "name-as-logged"
));
let no_stored_name_but_registered = result_with_name(project.id.clone(), None);
assert!(matches!(
resolve_project_name(&state, &no_stored_name_but_registered),
ProjectNameResolution::Current(name) if name == "current-name"
));
let removed = result_with_name(ProjectId::new(), None);
assert!(matches!(
resolve_project_name(&state, &removed),
ProjectNameResolution::Removed
));
}
#[test]
fn detail_project_name_shows_the_removed_label_when_nothing_resolves() {
let state = AppState::new(crate::config::AppConfig::default());
let removed = result_with_name(ProjectId::new(), None);
assert_eq!(
detail_project_name(&state, &removed),
state.t("history.removed_project")
);
}
#[test]
fn detail_project_name_shows_the_stored_name() {
let state = AppState::new(crate::config::AppConfig::default());
let result = result_with_name(ProjectId::new(), Some("dirty-1".to_owned()));
assert_eq!(detail_project_name(&state, &result), "dirty-1");
}
#[test]
fn project_name_matches_search_is_case_insensitive_and_never_matches_removed() {
let state = AppState::new(crate::config::AppConfig::default());
let named = result_with_name(ProjectId::new(), Some("Dirty-1".to_owned()));
let removed = result_with_name(ProjectId::new(), None);
assert!(project_name_matches_search(&state, &named, "dirty"));
assert!(!project_name_matches_search(&state, &named, "clean"));
assert!(!project_name_matches_search(&state, &removed, "dirty"));
}
#[test]
fn project_name_matches_search_finds_both_the_stored_and_the_current_name_after_a_rename() {
let project = Project::new("new-name", "/tmp/p");
let state = state_with_registered_project(&project);
let result = result_with_name(project.id.clone(), Some("old-name".to_owned()));
assert!(project_name_matches_search(&state, &result, "old"));
assert!(project_name_matches_search(&state, &result, "new"));
assert!(!project_name_matches_search(&state, &result, "other"));
}
#[test]
fn copied_log_names_uses_removed_project_in_english() {
let state = AppState::new(crate::config::AppConfig::default());
let result = sample_result(vec![result_with_name(ProjectId::new(), None)], false, None);
assert_eq!(
copied_log_names(&state, &result),
vec!["Removed project".to_owned()]
);
}
}