use iced::{
Alignment, Element, Length,
widget::{Space, button, column, container, row, scrollable, text},
};
use knotra_ui::widget::{
BUTTON_HEIGHT, FONT_BODY, FONT_SMALL, guided_button, guided_field, guided_field_focused,
};
use knotra_vcs::{
ContextTarget, ProjectId, VcsKind,
model::operation::{FreezeOutcome, ProjectOperationOutcome, SmartPullDisposition},
};
use crate::{
message::{
ChangelogMessage, ConflictOpsMessage, ContextMessage, FreezerMessage, Message, SyncMessage,
TagPushMessage,
},
state::AppState,
};
fn modal_shell<'a>(
title: &'a str,
close_msg: Option<Message>,
inner: Element<'a, Message>,
) -> Element<'a, Message> {
let close_btn = button(text("✕").size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 12])
.on_press_maybe(close_msg);
let header = row![
text(title).size(FONT_BODY + 2.0),
Space::new().width(Length::Fill),
close_btn,
]
.align_y(Alignment::Center);
container(
column![header, iced::widget::rule::horizontal(1), inner]
.spacing(16)
.padding(24),
)
.width(Length::Fill)
.max_width(580.0)
.into()
}
pub fn pull_modal(state: &AppState) -> Element<'_, Message> {
use crate::state::sync::SyncPhase;
let sync = &state.sync;
let inner: Element<'_, Message> = match &sync.phase {
SyncPhase::Idle | SyncPhase::Planning => column![
text(state.t("plain.get_latest.preparing")).size(FONT_BODY),
text(state.t("plain.get_latest.preparing_hint")).size(FONT_SMALL),
]
.spacing(8)
.into(),
SyncPhase::RetryPreparing => column![
text(state.t("plain.activity.retry_preparing")).size(FONT_BODY),
text(state.t("plain.get_latest.preparing_hint")).size(FONT_SMALL),
]
.spacing(8)
.into(),
SyncPhase::RetryPreparationFailed => {
let retry_message = match &state.activity.latest {
crate::state::LatestOpState::Completed {
log,
retry:
crate::state::RetryAvailability::Available(
crate::state::ActivityRetryAction::ReviewSmartPull { .. },
),
} => Some(Message::Activity(
crate::message::ActivityMessage::RetryRequested {
source_operation_id: log.result.operation_id.clone(),
},
)),
_ => None,
};
column![
text(state.t("plain.activity.retry_prepare_failed")).size(FONT_BODY),
row![
guided_button(state.t("plain.activity.review_retry"), retry_message, None,),
Space::new().width(Length::Fill),
button(text(state.t("action.close")).size(FONT_BODY))
.on_press(Message::Sync(SyncMessage::ModalClosed)),
]
.align_y(Alignment::Center),
]
.spacing(12)
.into()
}
SyncPhase::AwaitingConfirm(plan) => {
let mut rows: Vec<Element<'_, Message>> = Vec::new();
rows.push(
row![
text(state.t("plain.project"))
.size(FONT_SMALL)
.width(Length::FillPortion(3)),
text(state.t("plain.what_will_happen"))
.size(FONT_SMALL)
.width(Length::FillPortion(2)),
text(state.t("plain.note"))
.size(FONT_SMALL)
.width(Length::FillPortion(3)),
]
.spacing(8)
.into(),
);
for entry in &plan.entries {
let (action_label, note) = disposition_plain(
state,
entry.disposition.clone(),
entry.is_dirty,
entry.has_conflict,
entry.skip_reason.as_ref().map(|reason| reason.i18n_key()),
);
let action_cell: Element<'_, Message> =
if entry.is_dirty && !entry.has_conflict && entry.skip_reason.is_none() {
let curr = &entry.disposition;
row![
pick_disposition_btn(
state,
&entry.project_id,
SmartPullDisposition::FetchOnly,
state.t("plain.get_latest.check_only"),
curr == &SmartPullDisposition::FetchOnly
),
pick_disposition_btn(
state,
&entry.project_id,
SmartPullDisposition::StashAndPull,
state.t("plain.get_latest.get_anyway"),
curr == &SmartPullDisposition::StashAndPull
),
]
.spacing(4)
.into()
} else {
text(action_label)
.size(FONT_BODY)
.width(Length::FillPortion(2))
.into()
};
rows.push(
row![
text(&entry.project_name)
.size(FONT_BODY)
.width(Length::FillPortion(3)),
action_cell,
text(note).size(FONT_SMALL).width(Length::FillPortion(3)),
]
.spacing(8)
.align_y(Alignment::Center)
.into(),
);
}
for exclusion in &sync.retry_exclusions {
let name = state
.workspace
.as_ref()
.and_then(|workspace| {
workspace
.projects
.iter()
.find(|project| project.id == exclusion.project_id)
})
.map(|project| project.name.as_str())
.unwrap_or_else(|| state.t("plain.project"));
rows.push(
row![
text(name).size(FONT_BODY).width(Length::FillPortion(3)),
text(state.t("plain.activity.skipped"))
.size(FONT_BODY)
.width(Length::FillPortion(2)),
text(state.t(exclusion.reason.i18n_key()))
.size(FONT_SMALL)
.width(Length::FillPortion(3)),
]
.spacing(8)
.into(),
);
}
let has_work = plan
.entries
.iter()
.any(|e| !matches!(e.disposition, SmartPullDisposition::Excluded));
let can_start = has_work && !state.operation_interlock.is_busy();
let start_reason = if can_start {
None
} else if state.operation_interlock.is_busy() {
Some(state.t("plain.activity.busy"))
} else {
Some(state.t("plain.disabled.choose_one"))
};
let footer = row![
guided_button(
state.t("plain.get_latest.start"),
can_start.then_some(Message::Sync(SyncMessage::ExecuteRequested)),
start_reason,
),
Space::new().width(Length::Fill),
button(text(state.t("action.cancel")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Sync(SyncMessage::Cancelled)),
]
.align_y(Alignment::Center);
column![
text(state.t("plain.get_latest.review_heading")).size(FONT_BODY),
scrollable(column(rows).spacing(6)).height(Length::Fixed(240.0)),
footer,
]
.spacing(12)
.into()
}
SyncPhase::FetchRunning { done, total, .. } => {
let progress_text = format!(
"{} — {} {} {}",
state.t("plain.get_latest.working"),
done,
state.t("plain.of"),
total
);
column![text(progress_text).size(FONT_BODY),]
.spacing(8)
.into()
}
SyncPhase::PullRunning {
completed, plan, ..
} => {
let total = plan.entries.len();
let done = completed.len();
let mut result_rows: Vec<Element<'_, Message>> = completed
.iter()
.map(|p| {
let (icon, msg) = match p.result.effective_outcome() {
ProjectOperationOutcome::Succeeded => {
("✓", state.t("plain.get_latest.done_row"))
}
ProjectOperationOutcome::Failed => {
("!", state.t("plain.get_latest.needs_help_row"))
}
ProjectOperationOutcome::Skipped => {
("-", state.t("plain.get_latest.skipped_row"))
}
};
row![
text(icon).size(FONT_BODY).width(Length::Fixed(20.0)),
text(&p.project_name)
.size(FONT_BODY)
.width(Length::FillPortion(2)),
text(msg).size(FONT_BODY).width(Length::FillPortion(2)),
]
.spacing(8)
.into()
})
.collect();
for entry in plan.entries.iter().skip(done) {
result_rows.push(
row![
text("○").size(FONT_BODY).width(Length::Fixed(20.0)),
text(&entry.project_name)
.size(FONT_BODY)
.width(Length::FillPortion(2)),
text(state.t("plain.waiting"))
.size(FONT_SMALL)
.width(Length::FillPortion(2)),
]
.spacing(8)
.into(),
);
}
let progress_label = format!("{} of {} done", done, total);
column![
text(state.t("plain.get_latest.working")).size(FONT_BODY),
text(progress_label).size(FONT_SMALL),
scrollable(column(result_rows).spacing(6)).height(Length::Fixed(240.0)),
]
.spacing(12)
.into()
}
SyncPhase::Done(result) => pull_result_view(state, result),
};
let close_msg = if matches!(sync.phase, SyncPhase::PullRunning { .. }) {
None
} else {
Some(Message::Sync(SyncMessage::ModalClosed))
};
modal_shell(state.t("plain.get_latest"), close_msg, inner)
}
fn pull_result_view<'a>(
state: &'a AppState,
result: &'a crate::state::sync::SyncResult,
) -> Element<'a, Message> {
let ok = result.success_count();
let fail = result.fail_count();
let skipped = result.skipped_count();
let summary = if fail == 0 && skipped == 0 {
format!(
"{} {} {}.",
state.t("plain.get_latest.all_done_prefix"),
ok,
state.t("plain.get_latest.all_done_suffix")
)
} else if fail == 0 {
format!(
"{} {}. {} {}.",
ok,
state.t("plain.get_latest.done_count"),
skipped,
state.t("plain.get_latest.skipped_count")
)
} else {
format!(
"{} {}. {} {}. {} {}.",
ok,
state.t("plain.get_latest.done_count"),
fail,
state.t("plain.get_latest.needs_help_count"),
skipped,
state.t("plain.get_latest.skipped_count")
)
};
let body = if fail == 0 {
state.t("plain.no_next_step")
} else {
state.t("plain.get_latest.review_help_rows")
};
let rows: Vec<Element<'_, Message>> = result
.per_project
.iter()
.map(|pp| {
let (icon, msg) = match pp.outcome {
ProjectOperationOutcome::Succeeded => ("✓", state.t("plain.get_latest.done_row")),
ProjectOperationOutcome::Failed => ("!", state.t("plain.needs_help")),
ProjectOperationOutcome::Skipped => (
"-",
pp.skip_reason
.as_deref()
.unwrap_or(state.t("plain.get_latest.skipped_row")),
),
};
let mut row_col = column![
row![
text(icon).size(FONT_BODY).width(Length::Fixed(20.0)),
text(&pp.project_name)
.size(FONT_BODY)
.width(Length::FillPortion(2)),
text(msg).size(FONT_BODY).width(Length::FillPortion(2)),
]
.spacing(8),
]
.spacing(4);
if pp.outcome == ProjectOperationOutcome::Failed
&& !pp.commands_executed.is_empty()
&& state.show_op_details
{
for cmd in &pp.commands_executed {
row_col = row_col.push(text(format!(" {}", cmd)).size(FONT_SMALL));
}
if !pp.stderr.is_empty() {
row_col = row_col.push(
text(format!(" {}", pp.stderr.lines().next().unwrap_or("")))
.size(FONT_SMALL),
);
}
}
row_col.into()
})
.collect();
let details_label = if state.show_op_details {
state.t("plain.hide_details")
} else {
state.t("plain.show_details")
};
let footer = row![
button(text(details_label).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::ToggleOpDetails),
Space::new().width(Length::Fill),
button(text(state.t("action.close")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Sync(SyncMessage::ModalClosed)),
]
.align_y(Alignment::Center);
column![
text(summary).size(FONT_BODY + 2.0),
text(body).size(FONT_BODY),
scrollable(column(rows).spacing(8)).height(Length::Fixed(240.0)),
footer,
]
.spacing(12)
.into()
}
fn pick_disposition_btn<'a>(
_state: &'a AppState,
project_id: &'a ProjectId,
disposition: SmartPullDisposition,
label: &'a str,
selected: bool,
) -> Element<'a, Message> {
let btn = button(text(label).size(FONT_SMALL))
.height(32.0)
.padding([0, 10]);
let btn: Element<'a, Message> = if selected {
btn.into() } else {
btn.on_press(Message::Sync(SyncMessage::DispositionChanged(
project_id.clone(),
disposition,
)))
.into()
};
btn
}
fn disposition_plain(
state: &AppState,
d: SmartPullDisposition,
is_dirty: bool,
has_conflict: bool,
skip_reason_key: Option<&'static str>,
) -> (&'static str, &'static str) {
match d {
SmartPullDisposition::Pull => (state.t("plain.get_latest.action_get"), ""),
SmartPullDisposition::FetchOnly => (
state.t("plain.get_latest.action_check"),
if is_dirty {
state.t("plain.get_latest.note_unsaved")
} else {
""
},
),
SmartPullDisposition::StashAndPull => (
state.t("plain.get_latest.action_get_anyway"),
state.t("plain.get_latest.note_save_restore"),
),
SmartPullDisposition::Excluded => (
state.t("plain.get_latest.action_skip"),
if let Some(key) = skip_reason_key {
state.t(key)
} else if has_conflict {
state.t("plain.get_latest.note_needs_choice")
} else {
""
},
),
}
}
pub fn tag_modal(state: &AppState) -> Element<'_, Message> {
use crate::state::freezer::FreezerPhase;
let freezer = &state.freezer;
let inner: Element<'_, Message> = match &freezer.phase {
FreezerPhase::Idle | FreezerPhase::Validating { .. } => {
let name_error: Option<&str> = if freezer.freeze_name.is_empty() {
None } else if !freezer.freeze_name_is_valid() {
Some(state.t("plain.release.name_invalid"))
} else {
None
};
let name_field = guided_field_focused(
state.t("plain.release.name_label"),
state.t("plain.release.name_hint"),
&freezer.freeze_name,
|s| Message::Freezer(FreezerMessage::NameChanged(s)),
name_error,
knotra_ui::widget::focus_id::RELEASE_NAME.clone(),
);
let msg_field = guided_field(
state.t("plain.release.note_label"),
state.t("plain.release.note_hint"),
&freezer.tag_message,
|s| Message::Freezer(FreezerMessage::TagMessageChanged(s)),
None,
);
let validate_or_spinner: Element<'_, Message> =
if matches!(freezer.phase, FreezerPhase::Validating { .. }) {
text(state.t("plain.release.checking"))
.size(FONT_BODY)
.into()
} else if freezer.freeze_name_is_valid() {
guided_button(
state.t("plain.release.check_readiness"),
(!state.operation_interlock.is_busy())
.then_some(Message::Freezer(FreezerMessage::ValidateRequested)),
state
.operation_interlock
.is_busy()
.then_some(state.t("plain.activity.busy")),
)
} else {
Space::new().into()
};
column![name_field, msg_field, validate_or_spinner]
.spacing(14)
.into()
}
FreezerPhase::ValidationReady(validation) => {
let blocked_count = validation.blocked_count();
let ready_count = validation.ready_count();
let can_save =
validation.all_ready() && ready_count > 0 && !state.operation_interlock.is_busy();
let val_rows: Vec<Element<'_, Message>> = validation
.entries
.iter()
.map(|entry| {
let (icon, msg) = if entry.is_blocked() {
(
"!",
entry
.blockers
.first()
.map(|s| plain_blocker(state, s.as_str()))
.unwrap_or(""),
)
} else if !entry.included {
("—", state.t("plain.release.row_excluded"))
} else {
("✓", state.t("plain.release.row_ready"))
};
row![
text(icon).size(FONT_BODY).width(Length::Fixed(22.0)),
text(&entry.project_name)
.size(FONT_BODY)
.width(Length::FillPortion(2)),
text(msg).size(FONT_SMALL).width(Length::FillPortion(3)),
]
.spacing(8)
.align_y(Alignment::Center)
.into()
})
.collect();
let save_reason: Option<&str> = if state.operation_interlock.is_busy() {
Some(state.t("plain.activity.busy"))
} else if can_save {
None
} else if ready_count == 0 && blocked_count == 0 {
Some(state.t("plain.disabled.choose_one"))
} else if blocked_count == 1 {
Some(state.t("plain.release.fix_one"))
} else {
Some(state.t("plain.release.fix_some"))
};
let footer = row![
guided_button(
state.t("plain.save_release_point"),
can_save.then_some(Message::Freezer(FreezerMessage::ExecuteConfirmed)),
save_reason,
),
Space::new().width(Length::Fill),
button(text(state.t("action.cancel")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Freezer(FreezerMessage::BulkModalClosed)),
]
.align_y(Alignment::Center);
column![
text(state.t("plain.release.ready_check")).size(FONT_BODY),
scrollable(column(val_rows).spacing(6)).height(Length::Fixed(200.0)),
footer,
]
.spacing(12)
.into()
}
FreezerPhase::Executing => column![
text(state.t("plain.release.saving")).size(FONT_BODY),
text(state.t("plain.release.saving_hint")).size(FONT_SMALL),
]
.spacing(8)
.into(),
FreezerPhase::Done(result) => {
let push_is_running = state
.pending_tag_push
.as_ref()
.is_some_and(|push| push.is_pushing);
let outcome_title = match result.outcome {
FreezeOutcome::Success => state.t("plain.release.outcome_success"),
FreezeOutcome::RolledBack => state.t("plain.release.outcome_undone"),
FreezeOutcome::RollbackFailed => state.t("plain.release.outcome_partial"),
FreezeOutcome::NothingDone => state.t("plain.release.outcome_nothing"),
};
let outcome_body = match result.outcome {
FreezeOutcome::Success => state.t("plain.no_next_step"),
FreezeOutcome::RolledBack => state.t("plain.release.outcome_undone_hint"),
FreezeOutcome::RollbackFailed => state.t("plain.release.outcome_partial_hint"),
FreezeOutcome::NothingDone => "",
};
let rows: Vec<Element<'_, Message>> = result
.project_results
.iter()
.map(|pr| {
let icon = if pr.success {
"✓"
} else if pr.rollback_attempted && pr.rollback_succeeded == Some(true) {
"⟲"
} else {
"!"
};
let msg = if pr.success {
state.t("plain.release.row_saved")
} else if pr.rollback_attempted && pr.rollback_succeeded == Some(true) {
state.t("plain.release.row_undone")
} else {
state.t("plain.needs_help")
};
let mut row_col = column![
row![
text(icon).size(FONT_BODY).width(Length::Fixed(22.0)),
text(&pr.project_name)
.size(FONT_BODY)
.width(Length::FillPortion(2)),
text(msg).size(FONT_BODY).width(Length::FillPortion(2)),
]
.spacing(8),
]
.spacing(4);
if !pr.success
&& state.show_op_details
&& let Some(hint) = &pr.recovery_hint
{
for cmd in &hint.suggested_commands {
row_col = row_col.push(text(format!(" {}", cmd)).size(FONT_SMALL));
}
}
row_col.into()
})
.collect();
let details_label = if state.show_op_details {
state.t("plain.hide_details")
} else {
state.t("plain.show_details")
};
let push_offer: Element<'_, Message> = match &state.pending_tag_push {
Some(push)
if push.freeze_name == result.freeze_name && !push.project_ids.is_empty() =>
{
if push.is_pushing {
text(state.t("plain.release.sharing"))
.size(FONT_BODY)
.into()
} else {
column![
text(state.t("plain.release.share_offer")).size(FONT_BODY),
row![
button(text(state.t("plain.release.share_action")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press_maybe(
(!state.operation_interlock.is_busy()).then_some(
Message::TagPush(TagPushMessage::PushConfirmed),
)
),
button(
text(state.t("plain.release.share_decline")).size(FONT_BODY)
)
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::TagPush(TagPushMessage::PushDeclined)),
]
.spacing(8)
.align_y(Alignment::Center),
]
.spacing(8)
.into()
}
}
_ => Space::new().height(Length::Fixed(0.0)).into(),
};
let footer = row![
button(text(details_label).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::ToggleOpDetails),
Space::new().width(Length::Fill),
button(text(state.t("action.close")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press_maybe(
(!push_is_running)
.then_some(Message::Freezer(FreezerMessage::BulkModalClosed,))
),
]
.align_y(Alignment::Center);
column![
text(outcome_title).size(FONT_BODY + 2.0),
text(outcome_body).size(FONT_BODY),
scrollable(column(rows).spacing(8)).height(Length::Fixed(200.0)),
push_offer,
footer,
]
.spacing(12)
.into()
}
};
let close_msg = if matches!(freezer.phase, FreezerPhase::Executing)
|| state
.pending_tag_push
.as_ref()
.is_some_and(|push| push.is_pushing)
{
None
} else {
Some(Message::Freezer(FreezerMessage::BulkModalClosed))
};
modal_shell(state.t("plain.save_release_point"), close_msg, inner)
}
fn plain_blocker<'a>(state: &'a AppState, blocker: &str) -> &'a str {
let lower = blocker.to_lowercase();
if lower.contains("tag") && lower.contains("exist") {
state.t("plain.release.blocker_name_used")
} else if lower.contains("conflict") || lower.contains("merge") {
state.t("plain.release.blocker_needs_choice")
} else if lower.contains("dirty") || lower.contains("uncommitted") {
state.t("plain.release.blocker_unsaved")
} else {
state.t("plain.needs_help") }
}
fn context_target_kind_key(target: &ContextTarget) -> &'static str {
match target {
ContextTarget::GitLocalBranch { .. } | ContextTarget::Manual { .. } => {
"plain.switch.kind_local"
}
ContextTarget::GitRemoteBranch { .. } => "plain.switch.kind_shared",
ContextTarget::JjBookmark { .. } => "plain.switch.kind_saved_name",
ContextTarget::JjChange { .. } => "plain.switch.kind_change",
}
}
pub fn switch_modal(state: &AppState) -> Element<'_, Message> {
use crate::state::context::ContextPhase;
let ctx = &state.context_ops;
let inner: Element<'_, Message> = match &ctx.phase {
ContextPhase::Idle => column![text(state.t("plain.switch.no_project")).size(FONT_BODY)]
.spacing(8)
.into(),
ContextPhase::LoadingList(_) => column![
text(state.t("plain.status.checking")).size(FONT_BODY),
text(state.t("plain.switch.loading_hint")).size(FONT_SMALL),
]
.spacing(8)
.into(),
ContextPhase::BrowsingList {
project_id, search, ..
} => {
let search_field = guided_field_focused(
state.t("plain.switch.search_label"),
state.t("plain.switch.search_hint"),
search,
|s| Message::Context(ContextMessage::SearchChanged(s)),
None,
knotra_ui::widget::focus_id::SWITCH_TARGET.clone(),
);
let mut rows = column![search_field].spacing(8);
let candidates = ctx.filtered_candidates();
if candidates.is_empty() {
rows = rows.push(text(state.t("plain.switch.no_targets")).size(FONT_SMALL));
} else {
let mut list = column![].spacing(4);
for candidate in candidates {
let reason_key = candidate
.is_current
.then_some("plain.switch.reason_current");
let kind = state.t(context_target_kind_key(&candidate.target));
let detail = candidate.target.display_target();
let label = column![
text(candidate.label.as_str()).size(FONT_BODY),
text(format!("{kind} · {detail}")).size(FONT_SMALL),
]
.spacing(2);
let press = reason_key.is_none().then_some(Message::Context(
ContextMessage::SwitchTargetChosen(
project_id.clone(),
candidate.target.clone(),
candidate.label.clone(),
),
));
let mut row_col =
column![button(label).width(Length::Fill).on_press_maybe(press)];
if let Some(reason_key) = reason_key {
row_col = row_col.push(text(state.t(reason_key)).size(FONT_SMALL));
}
list = list.push(row_col.spacing(2));
}
rows = rows.push(scrollable(list).height(Length::Fixed(220.0)));
}
let footer = row![
Space::new().width(Length::Fill),
button(text(state.t("action.cancel")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Context(ContextMessage::BulkModalClosed)),
]
.align_y(Alignment::Center);
column![rows, footer].spacing(14).into()
}
ContextPhase::ConfirmSwitch {
project_name,
target_label,
target,
is_dirty,
disabled_reason_key,
..
} => {
let caution = if let Some(reason_key) = disabled_reason_key {
state.t(reason_key)
} else if *is_dirty {
state.t("plain.switch.dirty_hint")
} else {
state.t("plain.no_next_step")
};
let switch_msg = (disabled_reason_key.is_none()
&& !state.operation_interlock.is_busy())
.then_some(Message::Context(ContextMessage::SwitchConfirmed));
let footer = row![
guided_button(
state.t("plain.change_work_area"),
switch_msg,
if state.operation_interlock.is_busy() {
Some(state.t("plain.activity.busy"))
} else {
disabled_reason_key.map(|key| state.t(key))
},
),
Space::new().width(Length::Fill),
button(text(state.t("action.cancel")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Context(ContextMessage::SwitchCancelled)),
]
.align_y(Alignment::Center);
column![
text(project_name).size(FONT_BODY),
text(target_label).size(FONT_BODY),
text(state.t(context_target_kind_key(target))).size(FONT_SMALL),
text(caution).size(FONT_SMALL),
footer,
]
.spacing(12)
.into()
}
ContextPhase::Switching { target_label, .. } => column![
text(state.t("plain.switch.working")).size(FONT_BODY),
text(target_label).size(FONT_SMALL),
]
.spacing(8)
.into(),
ContextPhase::Done(result) => {
let (title, body) = if result.operation_result.success {
(
state.t("plain.switch.done_title"),
state.t("plain.no_next_step"),
)
} else {
(
state.t("plain.switch.failed_title"),
state.t("plain.switch.failed_hint"),
)
};
let mut detail_col = column![
text(title).size(FONT_BODY + 2.0),
text(result.target.as_str()).size(FONT_SMALL),
text(body).size(FONT_BODY),
]
.spacing(8);
if !result.operation_result.success && state.show_op_details {
if let Some(hint) = &result.recovery_hint {
detail_col = detail_col.push(text(hint.situation.as_str()).size(FONT_SMALL));
for cmd in &hint.suggested_commands {
detail_col = detail_col.push(text(format!(" {}", cmd)).size(FONT_SMALL));
}
}
for cmd in &result.operation_result.commands_executed {
detail_col = detail_col.push(text(format!(" {}", cmd)).size(FONT_SMALL));
}
}
let details_label = if state.show_op_details {
state.t("plain.hide_details")
} else {
state.t("plain.show_details")
};
let footer = row![
button(text(details_label).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::ToggleOpDetails),
Space::new().width(Length::Fill),
button(text(state.t("action.close")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Context(ContextMessage::BulkModalClosed)),
]
.align_y(Alignment::Center);
column![detail_col, footer].spacing(12).into()
}
};
let close_msg = (!matches!(ctx.phase, ContextPhase::Switching { .. }))
.then_some(Message::Context(ContextMessage::BulkModalClosed));
modal_shell(state.t("plain.change_work_area"), close_msg, inner)
}
pub fn resolve_panel<'a>(state: &'a AppState, project_id: &'a ProjectId) -> Element<'a, Message> {
let name = project_name_for(state, project_id);
let ops = &state.conflict_ops;
let git_actions_supported = conflict_actions_supported_for_project(state, project_id);
let abort_supported = git_actions_supported && project_has_git_merge_state(state, project_id);
let editor_configured = state.config.external_editor.is_some();
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 title = if *success {
state.t("plain.resolve.done")
} else {
state.t("plain.resolve.failed")
};
let details_label = if state.show_op_details {
state.t("plain.hide_details")
} else {
state.t("plain.show_details")
};
let mut result_col = column![
text(title).size(FONT_BODY + 2.0),
text(message).size(FONT_BODY),
]
.spacing(8)
.push(
button(text(details_label).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::ToggleOpDetails),
);
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 mark_control: Element<'_, Message> = if git_actions_supported {
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: f.path.clone(),
},
))
.into()
} else {
text(state.t("plain.resolve.unsupported"))
.size(FONT_SMALL)
.into()
};
column![
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)),
guided_button(
state.t("plain.resolve.open_editor"),
open_editor_msg,
editor_reason,
),
mark_control,
]
.align_y(Alignment::Center)
.spacing(6),
]
.spacing(4)
.into()
})
.collect();
scrollable(column(file_rows).spacing(8))
.height(Length::Fill)
.into()
}
} else {
text(state.t("plain.resolve.loading"))
.size(FONT_BODY)
.into()
}
}
};
let stop_control: Element<'_, Message> = if abort_supported {
button(text(state.t("plain.resolve.stop_attempt")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::ConflictOps(
ConflictOpsMessage::AbortMergeRequested(project_id.clone()),
))
.into()
} else {
Space::new().width(Length::Fixed(0.0)).into()
};
let close_msg = (!matches!(
ops.phase,
crate::state::conflict_ops::ConflictPhase::Operating { .. }
))
.then_some(Message::ConflictOps(ConflictOpsMessage::PanelClosed));
let footer = row![
stop_control,
Space::new().width(Length::Fill),
button(text(state.t("action.close")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press_maybe(close_msg.clone()),
]
.align_y(Alignment::Center);
container(
column![
row![
text(format!("{} — {}", state.t("plain.resolve.title"), name))
.size(FONT_BODY + 2.0),
Space::new().width(Length::Fill),
button(text("✕").size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 12])
.on_press_maybe(close_msg),
]
.align_y(Alignment::Center),
text(state.t("plain.resolve.instruction")).size(FONT_BODY),
content,
footer,
]
.spacing(14)
.padding(20),
)
.width(Length::Fixed(340.0))
.height(Length::Fill)
.into()
}
fn conflict_actions_supported_for_project(state: &AppState, project_id: &ProjectId) -> bool {
state
.workspace_status
.as_ref()
.and_then(|ws| {
ws.projects
.iter()
.find(|status| &status.project_id == project_id)
})
.map(|status| status.identity.vcs_kind == VcsKind::Git)
.unwrap_or_else(|| {
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(".jj").is_dir() && path.join(".git").exists()
})
.unwrap_or(false)
})
}
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)
}
pub fn changelog_modal(state: &AppState) -> Element<'_, Message> {
use crate::state::changelog::ChangelogPhase;
let cl = &state.changelog;
let is_collecting = matches!(cl.phase, ChangelogPhase::Collecting);
let since_field = guided_field(
state.t("plain.changelog.since_label"),
state.t("plain.changelog.since_hint"),
&cl.since_ref,
|s| Message::Changelog(ChangelogMessage::SinceRefChanged(s)),
None,
);
let project_picker = changelog_project_picker(state, is_collecting);
let content: Element<'_, Message> = match &cl.phase {
ChangelogPhase::Idle => {
let reason = if cl.since_ref.trim().is_empty() {
Some(state.t("plain.changelog.reason_empty"))
} else if cl.selected_ids().is_empty() {
Some(state.t("plain.disabled.choose_one"))
} else {
None
};
guided_button(
state.t("plain.changelog.generate"),
cl.is_ready_to_collect()
.then_some(Message::Changelog(ChangelogMessage::CollectRequested)),
reason,
)
}
ChangelogPhase::Collecting => text(state.t("plain.changelog.collecting"))
.size(FONT_BODY)
.into(),
ChangelogPhase::Ready(draft) => {
let counts = changelog_result_counts(draft);
let preview_text = changelog_markdown_preview(draft);
let mut result_col = column![
text(changelog_summary_text(state, counts)).size(FONT_BODY),
changelog_result_notice(state, draft, counts),
changelog_project_results(state, draft, counts),
scrollable(text(preview_text).size(FONT_SMALL)).height(Length::Fixed(240.0)),
]
.spacing(8);
if draft.projects.is_empty() {
result_col = result_col.push(text(state.t("plain.changelog.no_projects")));
}
column![
result_col,
row![
button(text(state.t("plain.changelog.copy")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Changelog(ChangelogMessage::CopyRequested)),
Space::new().width(Length::Fill),
button(text(state.t("action.close")).size(FONT_BODY))
.height(BUTTON_HEIGHT)
.padding([0, 18])
.on_press(Message::Changelog(ChangelogMessage::ModalClosed)),
]
.align_y(Alignment::Center)
.spacing(8),
]
.spacing(10)
.into()
}
};
let inner = column![since_field, project_picker, content].spacing(14);
modal_shell(
state.t("plain.changelog.title"),
Some(Message::Changelog(ChangelogMessage::ModalClosed)),
inner.into(),
)
}
fn changelog_project_picker(state: &AppState, disabled: bool) -> Element<'_, Message> {
let Some(workspace) = &state.workspace else {
return text(state.t("plain.changelog.no_projects"))
.size(FONT_SMALL)
.into();
};
if workspace.projects.is_empty() {
return text(state.t("plain.changelog.no_projects"))
.size(FONT_SMALL)
.into();
}
let mut rows =
column![text(state.t("plain.changelog.projects_label")).size(FONT_SMALL)].spacing(6);
for project in &workspace.projects {
let included = state
.changelog
.project_selection
.get(&project.id)
.copied()
.unwrap_or(false);
let marker = if included { "☑" } else { "☐" };
let label = format!("{marker} {}", project.name);
let msg = (!disabled).then_some(Message::Changelog(ChangelogMessage::ProjectToggled(
project.id.clone(),
!included,
)));
rows = rows.push(
button(text(label).size(FONT_SMALL))
.height(BUTTON_HEIGHT)
.padding([0, 12])
.on_press_maybe(msg),
);
}
rows.into()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ChangelogResultCounts {
pub total_commits: usize,
pub projects_with_commits: usize,
pub projects_without_changes: usize,
pub projects_with_errors: usize,
}
pub(crate) fn changelog_result_counts(draft: &knotra_vcs::ChangelogDraft) -> ChangelogResultCounts {
ChangelogResultCounts {
total_commits: draft.total_commits(),
projects_with_commits: draft
.projects
.iter()
.filter(|project| !project.entries.is_empty() && project.error.is_none())
.count(),
projects_without_changes: draft
.projects
.iter()
.filter(|project| project.entries.is_empty() && project.error.is_none())
.count(),
projects_with_errors: draft
.projects
.iter()
.filter(|project| project.error.is_some())
.count(),
}
}
pub(crate) fn changelog_markdown_preview(draft: &knotra_vcs::ChangelogDraft) -> String {
draft.to_markdown()
}
fn changelog_summary_text(state: &AppState, counts: ChangelogResultCounts) -> String {
format!(
"{} {} · {} {} · {} {} · {} {}",
counts.total_commits,
state.t("plain.changelog.summary_commits"),
counts.projects_with_commits,
state.t("plain.changelog.summary_with_notes"),
counts.projects_without_changes,
state.t("plain.changelog.summary_no_changes"),
counts.projects_with_errors,
state.t("plain.changelog.summary_failed")
)
}
fn changelog_result_notice<'a>(
state: &'a AppState,
draft: &knotra_vcs::ChangelogDraft,
counts: ChangelogResultCounts,
) -> Element<'a, Message> {
let all_failed =
!draft.projects.is_empty() && counts.projects_with_errors == draft.projects.len();
let notice = if all_failed {
state.t("plain.changelog.all_failed")
} else if counts.projects_with_errors > 0 {
state.t("plain.changelog.some_failed")
} else if counts.total_commits == 0 {
state.t("plain.changelog.no_changes_found")
} else {
state.t("plain.changelog.ready")
};
text(notice).size(FONT_SMALL).into()
}
fn changelog_project_results<'a>(
state: &'a AppState,
draft: &knotra_vcs::ChangelogDraft,
counts: ChangelogResultCounts,
) -> Element<'a, Message> {
let mut rows = column![].spacing(4);
if counts.projects_without_changes > 0 {
let names = draft
.projects
.iter()
.filter(|project| project.entries.is_empty() && project.error.is_none())
.map(|project| project.project_name.as_str())
.collect::<Vec<_>>()
.join(", ");
rows = rows.push(
text(format!(
"{} {}",
state.t("plain.changelog.no_change_projects"),
names
))
.size(FONT_SMALL),
);
}
for project in draft
.projects
.iter()
.filter(|project| project.error.is_some())
{
let error = project.error.as_deref().unwrap_or_default();
rows = rows.push(
text(format!(
"{}: {}",
project.project_name,
if error.is_empty() {
state.t("plain.changelog.project_failed")
} else {
error
}
))
.size(FONT_SMALL),
);
}
rows.into()
}
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())
}