[Imp] UI & UX

This commit is contained in:
Alex 2026-07-28 02:20:15 +02:00
commit 7399cf8fc3
Signed by: alex
SSH key fingerprint: SHA256:D1+Ub8o0v4K5y1JNivW8IxEOelqLSvPmUzBbDIoZkRQ
18 changed files with 1635 additions and 193 deletions

View file

@ -0,0 +1,271 @@
use crossterm::event::KeyCode;
use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph},
};
use crate::{
controls::button::{ActionButton, ButtonIntent, render_button},
interaction_result::InteractionResult,
render_context::RenderContext,
screens::screens::{HitMap, KeyHint, Screen, UiEvent},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DialogButton {
Cancel,
Confirm,
Custom(usize),
}
pub struct ConfirmDialog {
title: String,
message: Vec<String>,
buttons: Vec<DialogButtonConfig>,
focused_button: usize,
on_confirm: Option<Box<dyn Fn() -> InteractionResult + Send + Sync>>,
on_cancel: Option<Box<dyn Fn() -> InteractionResult + Send + Sync>>,
}
struct DialogButtonConfig {
label: String,
intent: ButtonIntent,
enabled: bool,
}
impl ConfirmDialog {
pub fn new(title: impl Into<String>, message: impl Into<String>) -> Self {
Self {
title: title.into(),
message: vec![message.into()],
buttons: vec![
DialogButtonConfig {
label: "Cancel".to_owned(),
intent: ButtonIntent::Cancel,
enabled: true,
},
DialogButtonConfig {
label: "Confirm".to_owned(),
intent: ButtonIntent::Primary,
enabled: true,
},
],
focused_button: 0,
on_confirm: None,
on_cancel: None,
}
}
pub fn destructive(title: impl Into<String>, message: impl Into<String>) -> Self {
Self {
title: title.into(),
message: vec![message.into()],
buttons: vec![
DialogButtonConfig {
label: "Cancel".to_owned(),
intent: ButtonIntent::Cancel,
enabled: true,
},
DialogButtonConfig {
label: "Delete".to_owned(),
intent: ButtonIntent::Destructive,
enabled: true,
},
],
focused_button: 0,
on_confirm: None,
on_cancel: None,
}
}
pub fn with_message_line(mut self, line: impl Into<String>) -> Self {
self.message.push(line.into());
self
}
pub fn with_button(mut self, label: impl Into<String>, intent: ButtonIntent) -> Self {
self.buttons.push(DialogButtonConfig {
label: label.into(),
intent,
enabled: true,
});
self
}
pub fn with_confirm_action<F: Fn() -> InteractionResult + Send + Sync + 'static>(
mut self,
action: F,
) -> Self {
self.on_confirm = Some(Box::new(action));
self
}
pub fn with_cancel_action<F: Fn() -> InteractionResult + Send + Sync + 'static>(
mut self,
action: F,
) -> Self {
self.on_cancel = Some(Box::new(action));
self
}
fn activate(&self) -> InteractionResult {
match self.focused_button {
0 => {
if let Some(action) = &self.on_cancel {
action()
} else {
InteractionResult::CloseScreen
}
}
1 => {
if let Some(action) = &self.on_confirm {
action()
} else {
InteractionResult::CloseScreen
}
}
_ => InteractionResult::CloseScreen,
}
}
fn next_button(&mut self) {
self.focused_button = (self.focused_button + 1) % self.buttons.len();
}
fn prev_button(&mut self) {
if self.focused_button == 0 {
self.focused_button = self.buttons.len() - 1;
} else {
self.focused_button -= 1;
}
}
}
impl Screen for ConfirmDialog {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn render(&self, f: &mut Frame, rect: Rect, context: &RenderContext<'_>, _hits: &mut HitMap) {
let area = crate::layout::fit::centered_rect(
rect,
crate::layout::fit::RequiredSize {
width: 50,
height: (self.message.len() + 8) as u16,
},
);
f.render_widget(Clear, area);
let block = Block::default()
.title(format!(" {} ", self.title))
.borders(Borders::ALL)
.border_style(context.theme.borders.focused)
.style(context.theme.surfaces.overlay);
let inner = block.inner(area);
f.render_widget(block, area);
let rows = Layout::vertical([
Constraint::Min(self.message.len() as u16),
Constraint::Length(1),
Constraint::Length(1),
])
.split(inner);
let lines: Vec<Line> = self
.message
.iter()
.map(|line| Line::from(Span::styled(line.as_str(), context.theme.text.normal)))
.collect();
f.render_widget(Paragraph::new(lines), rows[0]);
let buttons_area = rows[2];
let button_widths: Vec<u16> = self
.buttons
.iter()
.map(|b| {
crate::controls::button::button_minimum_width(&b.label)
})
.collect();
let total_width: u16 = button_widths.iter().sum();
let spacing = self.buttons.len().saturating_sub(1) as u16;
let available = buttons_area.width;
let start_x = buttons_area.x + available.saturating_sub(total_width + spacing) / 2;
let mut x = start_x;
for (i, (button_config, &width)) in
self.buttons.iter().zip(&button_widths).enumerate()
{
let button_area = Rect {
x,
y: buttons_area.y,
width,
height: 1,
};
x = x.saturating_add(width + 1);
render_button(
f,
button_area,
ActionButton {
label: &button_config.label,
intent: button_config.intent,
focused: self.focused_button == i,
enabled: button_config.enabled,
},
context.theme,
);
}
}
fn handle_event(&mut self, event: UiEvent) -> InteractionResult {
let UiEvent::Key(key) = event else {
return InteractionResult::Unhandled;
};
match key.code {
KeyCode::Esc => InteractionResult::CloseScreen,
KeyCode::Tab => {
self.next_button();
InteractionResult::Handled
}
KeyCode::BackTab => {
self.prev_button();
InteractionResult::Handled
}
KeyCode::Left => {
self.prev_button();
InteractionResult::Handled
}
KeyCode::Right => {
self.next_button();
InteractionResult::Handled
}
KeyCode::Enter | KeyCode::Char(' ') => self.activate(),
_ => InteractionResult::Unhandled,
}
}
fn key_hints(&self) -> Vec<KeyHint> {
vec![
KeyHint {
keys: "Tab",
action: "Switch button",
},
KeyHint {
keys: "Enter",
action: "Confirm",
},
KeyHint {
keys: "Esc",
action: "Cancel",
},
]
}
}

View file

@ -1,25 +1,58 @@
use crate::ipc_client::{DaemonStatus, IpcConnectionState};
use crate::theme::ResolvedTheme;
use crate::{
controls::button::{ActionButton, ButtonIntent, render_button},
controls::button::ButtonIntent,
screens::screens::{AppAction, HitMap},
};
use ratatui::{
Frame,
layout::{Constraint, Layout, Rect},
text::Span,
text::{Line, Span},
widgets::Paragraph,
};
/// Shared application bar. The brand cell is deliberately an action so it is
/// a reliable way home from every screen.
fn connection_badge(state: &IpcConnectionState, theme: &ResolvedTheme) -> (&'static str, ratatui::style::Style) {
match state {
IpcConnectionState::Connected => ("OK", theme.status.success),
IpcConnectionState::Connecting => ("..", theme.status.warning),
IpcConnectionState::Reconnecting { .. } => ("WARN", theme.status.warning),
IpcConnectionState::Failed { .. } | IpcConnectionState::Incompatible { .. } => ("FAIL", theme.status.error),
IpcConnectionState::Disconnected => ("WARN", theme.status.warning),
}
}
fn omikron_badge(daemon: &DaemonStatus, theme: &ResolvedTheme) -> (String, ratatui::style::Style) {
use iota_ipc::ComponentId;
let health = daemon.components.get(&ComponentId::Omikron);
let (label, style) = match health.map(|h| h.status) {
Some(iota_ipc::HealthStatus::Healthy) => ("OK", theme.status.success),
Some(iota_ipc::HealthStatus::Degraded) => ("WARN", theme.status.warning),
Some(iota_ipc::HealthStatus::Failed) => ("FAIL", theme.status.error),
None => ("--", theme.text.muted),
};
let detail = health
.and_then(|h| h.message.as_deref())
.map(|m| format!(" {m}"))
.unwrap_or_default();
(format!("{label}{detail}"), style)
}
pub fn render_header(
frame: &mut Frame,
area: Rect,
title: &str,
connection: &IpcConnectionState,
daemon: &DaemonStatus,
theme: &ResolvedTheme,
hits: &mut HitMap,
focused_action: Option<usize>,
) {
let version = if daemon.version.is_empty() {
String::new()
} else {
format!(" v{}", daemon.version)
};
let rows = Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)]).split(area);
let cells = Layout::horizontal([
Constraint::Min(28),
Constraint::Length(12),
@ -27,36 +60,75 @@ pub fn render_header(
Constraint::Length(12),
Constraint::Length(8),
])
.split(area);
.split(rows[0]);
let cells2 = Layout::horizontal([
Constraint::Min(28),
Constraint::Length(12),
Constraint::Length(12),
Constraint::Length(12),
Constraint::Length(8),
])
.split(rows[1]);
let (ipc_label, ipc_style) = connection_badge(connection, theme);
let (omikron_text, omikron_style) = omikron_badge(daemon, theme);
let brand_line1 = Line::from(vec![
Span::styled(format!(" IOTA{version}"), theme.surfaces.toolbar),
Span::styled(format!(" IPC:[{ipc_label}]"), ipc_style),
]);
let brand_line2 = Line::from(vec![
Span::styled(" Omikron: ", theme.surfaces.toolbar),
Span::styled(format!("[{omikron_text}]"), omikron_style),
]);
let brand_area = Rect {
x: area.x,
y: area.y,
width: cells[0].width,
height: area.height,
};
frame.render_widget(
Paragraph::new(Span::styled(format!(" {title}"), theme.surfaces.toolbar)),
cells[0],
Paragraph::new(vec![brand_line1, brand_line2]).style(theme.surfaces.toolbar),
brand_area,
);
hits.register(cells[0], AppAction::OpenMain);
for (index, (area, label, action)) in [
(cells[1], "Overview", AppAction::OpenOverview),
(cells[2], "Users", AppAction::OpenUsers),
(cells[3], "Settings", AppAction::OpenSettings),
(cells[4], "Quit", AppAction::Quit),
hits.register(brand_area, AppAction::OpenMain);
for (index, (top, _bottom, label, intent, action)) in [
(cells[1], cells2[1], "Overview", ButtonIntent::Primary, AppAction::OpenOverview),
(cells[2], cells2[2], "Users", ButtonIntent::Neutral, AppAction::OpenUsers),
(cells[3], cells2[3], "Settings", ButtonIntent::Neutral, AppAction::OpenSettings),
(cells[4], cells2[4], "Quit", ButtonIntent::Destructive, AppAction::Quit),
]
.into_iter()
.enumerate()
{
render_button(
frame,
area,
ActionButton {
label,
intent: if action == AppAction::Quit {
ButtonIntent::Destructive
} else {
ButtonIntent::Neutral
},
focused: focused_action == Some(index),
enabled: true,
},
theme,
let button_area = Rect {
x: top.x,
y: top.y,
width: top.width,
height: area.height,
};
let style = match (intent, focused_action == Some(index)) {
(ButtonIntent::Primary, true) => theme.buttons.primary_focused,
(ButtonIntent::Primary, false) => theme.buttons.primary,
(ButtonIntent::Neutral, true) => theme.buttons.neutral_focused,
(ButtonIntent::Neutral, false) => theme.buttons.neutral,
(ButtonIntent::Cancel, true) => theme.buttons.cancel_focused,
(ButtonIntent::Cancel, false) => theme.buttons.cancel,
(ButtonIntent::Destructive, _) => theme.buttons.destructive,
};
let display_label = if focused_action == Some(index) {
format!(" {label}")
} else {
label.to_owned()
};
frame.render_widget(
Paragraph::new(vec![
Line::from(Span::styled(display_label, style)),
Line::from(""),
]),
button_area,
);
hits.register(area, action);
hits.register(button_area, action);
}
}

View file

@ -2,6 +2,7 @@ pub mod action;
pub mod button;
pub mod checkbox_group;
pub mod choice;
pub mod dialog;
pub mod header;
pub mod navigation;
pub mod panel;

View file

@ -0,0 +1,219 @@
use crossterm::event::KeyCode;
use ratatui::{
Frame,
layout::Rect,
text::{Line, Span},
widgets::{Block, Borders, Clear, Paragraph},
};
use crate::{
interaction_result::InteractionResult,
render_context::RenderContext,
screens::screens::{HitMap, Screen, UiEvent},
theme::ResolvedTheme,
};
pub struct HelpOverlay {
scroll: usize,
}
impl HelpOverlay {
pub fn new() -> Self {
Self { scroll: 0 }
}
fn build_lines(&self, theme: &ResolvedTheme) -> Vec<Line<'static>> {
vec![
Line::from(""),
Line::from(Span::styled(
"Global Keyboard Shortcuts",
theme.text.heading,
)),
Line::from(""),
Line::from(vec![
Span::styled(" F6", theme.text.link),
Span::styled(" Toggle header navigation", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Tab", theme.text.link),
Span::styled(" Move focus to next panel", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Shift+Tab", theme.text.link),
Span::styled(" Move focus to previous panel", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Esc", theme.text.link),
Span::styled(" Go back / Close dialog", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Ctrl+C", theme.text.link),
Span::styled(" Quit the application", theme.text.normal),
]),
Line::from(""),
Line::from(Span::styled("Dashboard Navigation", theme.text.heading)),
Line::from(""),
Line::from(vec![
Span::styled(" o/O", theme.text.link),
Span::styled(" Open Overview screen", theme.text.normal),
]),
Line::from(vec![
Span::styled(" u/U", theme.text.link),
Span::styled(" Open Users screen", theme.text.normal),
]),
Line::from(vec![
Span::styled(" m/M", theme.text.link),
Span::styled(" Open Metrics screen", theme.text.normal),
]),
Line::from(""),
Line::from(Span::styled("Log Panel", theme.text.heading)),
Line::from(""),
Line::from(vec![
Span::styled(" j/Down", theme.text.link),
Span::styled(" Scroll down", theme.text.normal),
]),
Line::from(vec![
Span::styled(" k/Up", theme.text.link),
Span::styled(" Scroll up", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Enter", theme.text.link),
Span::styled(" Lock/unlock scroll", theme.text.normal),
]),
Line::from(vec![
Span::styled(" /", theme.text.link),
Span::styled(" Filter logs", theme.text.normal),
]),
Line::from(""),
Line::from(Span::styled("Console Panel", theme.text.heading)),
Line::from(""),
Line::from(vec![
Span::styled(" Enter", theme.text.link),
Span::styled(" Send command", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Up/Down", theme.text.link),
Span::styled(" Command history", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Tab", theme.text.link),
Span::styled(" Auto-complete", theme.text.normal),
]),
Line::from(vec![
Span::styled(" /help", theme.text.link),
Span::styled(" List available commands", theme.text.normal),
]),
Line::from(""),
Line::from(Span::styled("List Navigation", theme.text.heading)),
Line::from(""),
Line::from(vec![
Span::styled(" j/Down", theme.text.link),
Span::styled(" Next item", theme.text.normal),
]),
Line::from(vec![
Span::styled(" k/Up", theme.text.link),
Span::styled(" Previous item", theme.text.normal),
]),
Line::from(vec![
Span::styled(" PgUp/PgDn", theme.text.link),
Span::styled(" Page up/down", theme.text.normal),
]),
Line::from(vec![
Span::styled(" Home", theme.text.link),
Span::styled(" First item", theme.text.normal),
]),
Line::from(vec![
Span::styled(" End", theme.text.link),
Span::styled(" Last item", theme.text.normal),
]),
Line::from(vec![
Span::styled(" /", theme.text.link),
Span::styled(" Filter list", theme.text.normal),
]),
Line::from(""),
Line::from(Span::styled(
"Press ? or Esc to close this overlay",
theme.text.muted,
)),
]
}
}
impl Screen for HelpOverlay {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn render(&self, f: &mut Frame, rect: Rect, context: &RenderContext<'_>, _hits: &mut HitMap) {
let area = crate::layout::fit::centered_rect(
rect,
crate::layout::fit::RequiredSize {
width: 52,
height: 40,
},
);
f.render_widget(Clear, area);
let block = Block::default()
.title(" Keyboard Shortcuts (?) ")
.borders(Borders::ALL)
.border_style(context.theme.borders.focused)
.style(context.theme.surfaces.overlay);
let inner = block.inner(area);
f.render_widget(block, area);
let lines = self.build_lines(context.theme);
let paragraph = Paragraph::new(lines)
.scroll((self.scroll as u16, 0))
.style(context.theme.text.normal);
f.render_widget(paragraph, inner);
}
fn handle_event(&mut self, event: UiEvent) -> InteractionResult {
let UiEvent::Key(key) = event else {
return InteractionResult::Unhandled;
};
match key.code {
KeyCode::Esc | KeyCode::Char('?') | KeyCode::Char('q') => {
InteractionResult::CloseScreen
}
KeyCode::Down | KeyCode::Char('j') => {
self.scroll = self.scroll.saturating_add(1);
InteractionResult::Handled
}
KeyCode::Up | KeyCode::Char('k') => {
self.scroll = self.scroll.saturating_sub(1);
InteractionResult::Handled
}
KeyCode::PageDown => {
self.scroll = self.scroll.saturating_add(10);
InteractionResult::Handled
}
KeyCode::PageUp => {
self.scroll = self.scroll.saturating_sub(10);
InteractionResult::Handled
}
_ => InteractionResult::Unhandled,
}
}
fn key_hints(&self) -> Vec<crate::screens::screens::KeyHint> {
vec![
crate::screens::screens::KeyHint {
keys: "Up/Down",
action: "Scroll",
},
crate::screens::screens::KeyHint {
keys: "Esc/?",
action: "Close",
},
]
}
}
use std::any::Any;

View file

@ -23,10 +23,12 @@ pub mod util {
}
pub mod app_state;
pub mod controls;
pub mod help_overlay;
pub mod input_handler;
pub mod interaction_result;
pub mod ipc_client;
pub mod layout;
pub mod notification;
pub mod render_context;
pub mod theme;
pub mod ui;

View file

@ -0,0 +1,128 @@
use std::time::{Duration, Instant};
use ratatui::{
Frame,
layout::Rect,
text::{Line, Span},
widgets::Paragraph,
};
use crate::theme::ResolvedTheme;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationKind {
Success,
Warning,
Error,
Info,
}
#[derive(Clone)]
pub struct Notification {
pub message: String,
pub kind: NotificationKind,
pub created_at: Instant,
pub duration: Duration,
}
impl Notification {
pub fn success(message: impl Into<String>) -> Self {
Self::new(message, NotificationKind::Success, Duration::from_secs(3))
}
pub fn warning(message: impl Into<String>) -> Self {
Self::new(message, NotificationKind::Warning, Duration::from_secs(4))
}
pub fn error(message: impl Into<String>) -> Self {
Self::new(message, NotificationKind::Error, Duration::from_secs(5))
}
pub fn info(message: impl Into<String>) -> Self {
Self::new(message, NotificationKind::Info, Duration::from_secs(3))
}
fn new(message: impl Into<String>, kind: NotificationKind, duration: Duration) -> Self {
Self {
message: message.into(),
kind,
created_at: Instant::now(),
duration,
}
}
pub fn is_expired(&self) -> bool {
self.created_at.elapsed() >= self.duration
}
pub fn remaining(&self) -> Duration {
self.duration.saturating_sub(self.created_at.elapsed())
}
pub fn progress(&self) -> f64 {
let elapsed = self.created_at.elapsed().as_secs_f64();
let total = self.duration.as_secs_f64();
(elapsed / total).min(1.0)
}
}
pub fn render_notification(
frame: &mut Frame,
area: Rect,
notification: &Notification,
theme: &ResolvedTheme,
) {
let (prefix, style) = match notification.kind {
NotificationKind::Success => ("", theme.status.success),
NotificationKind::Warning => ("", theme.status.warning),
NotificationKind::Error => ("", theme.status.error),
NotificationKind::Info => (" ", theme.status.info),
};
let remaining = notification.remaining().as_secs();
let progress = notification.progress();
let mut spans = vec![
Span::styled(prefix, style),
Span::styled(&notification.message, theme.text.normal),
];
if remaining > 0 {
let bar_width = 10;
let filled = ((1.0 - progress) * bar_width as f64) as usize;
let empty = bar_width - filled;
let bar: String = "".repeat(filled) + &"".repeat(empty);
spans.push(Span::styled(
format!(" [{bar}] {remaining}s"),
theme.text.muted,
));
}
let paragraph = Paragraph::new(Line::from(spans));
frame.render_widget(paragraph, area);
}
pub fn render_notification_area(
frame: &mut Frame,
area: Rect,
notifications: &[Notification],
theme: &ResolvedTheme,
) {
if notifications.is_empty() {
return;
}
let visible_height = area.height as usize;
let start = notifications.len().saturating_sub(visible_height);
let visible = &notifications[start..];
for (i, notification) in visible.iter().enumerate() {
let row = Rect {
x: area.x,
y: area.y + i as u16,
width: area.width,
height: 1,
};
render_notification(frame, row, notification, theme);
}
}

View file

@ -49,28 +49,6 @@ impl MainScreen {
pub fn daemon_status(&self) -> watch::Receiver<DaemonStatus> {
self.daemon_status_rx.clone()
}
fn status_summary(&self) -> String {
let connection = match self.connection_status_rx.borrow().clone() {
IpcConnectionState::Connected => "[OK] Connected".to_owned(),
IpcConnectionState::Connecting => "[..] Connecting".to_owned(),
IpcConnectionState::Reconnecting { .. } => "[WARN] Reconnecting".to_owned(),
IpcConnectionState::Failed { .. } | IpcConnectionState::Incompatible { .. } => {
"[FAIL] Failed".to_owned()
}
IpcConnectionState::Disconnected => "[WARN] Disconnected".to_owned(),
};
let daemon = self.daemon_status_rx.borrow().clone();
let version = if daemon.version.is_empty() {
String::new()
} else {
format!(" v{}", daemon.version)
};
let ready = daemon
.startup_phase
.map(|phase| format!(" {:?}", phase))
.unwrap_or_default();
format!("IOTA{version} {connection}{ready}")
}
pub async fn new(ui: Arc<UI>) -> Self {
let mut elements: Vec<Box<dyn InteractableElement>> = Vec::new();
@ -254,39 +232,6 @@ impl Screen for MainScreen {
fn render(&self, f: &mut Frame, rect: Rect, context: &RenderContext<'_>, hits: &mut HitMap) {
self.layout_width.store(rect.width, Ordering::Relaxed);
// A watch Ref blocks senders until it is dropped. Rendering may do
// terminal I/O, so retain only owned snapshots for the whole frame.
let status = self.connection_status_rx.borrow().clone();
let daemon = self.daemon_status_rx.borrow().clone();
let status_text = match status {
IpcConnectionState::Connected => "Connected".to_string(),
IpcConnectionState::Connecting => "Connecting...".to_string(),
IpcConnectionState::Reconnecting { attempt } => {
format!("Reconnecting (attempt {})...", attempt)
}
IpcConnectionState::Incompatible { message } => {
format!("Incompatible protocol: {}", message)
}
IpcConnectionState::Failed { message } => {
format!("Connection failed: {}", message)
}
IpcConnectionState::Disconnected => "Disconnected".to_string(),
};
let readiness = daemon
.startup_phase
.map(|phase| format!("{:?}", phase))
.unwrap_or_else(|| "Waiting for status".into());
let health = daemon
.degraded_reason
.as_deref()
.map(|reason| format!("{reason}"))
.unwrap_or_default();
let version = if daemon.version.is_empty() {
String::new()
} else {
format!(" v{}", daemon.version)
};
let _ = (status_text, readiness, health, version);
f.render_widget(
ratatui::widgets::Block::default().style(context.theme.surfaces.canvas),
rect,
@ -503,9 +448,6 @@ impl Screen for MainScreen {
_ => InteractionResult::Unhandled,
}
}
fn app_title(&self) -> String {
self.status_summary()
}
fn key_hints(&self) -> Vec<KeyHint> {
if self.selected_coords == (2, 0) {
vec![

View file

@ -30,6 +30,8 @@ pub enum AppEvent {
theme: crate::theme::ThemeName,
color: crate::theme::TerminalPolicy,
unicode: crate::theme::TerminalPolicy,
cli_output: crate::theme::CliOutputFormat,
cli_require_confirmation: bool,
},
ThemeSaved(Result<(), String>),
UsersLoaded(Result<Vec<crate::screens::users::UserEntry>, String>),
@ -118,9 +120,6 @@ pub trait Screen: Send + Sync + Any {
fn handle_action(&mut self, _action: AppAction) -> InteractionResult {
InteractionResult::Unhandled
}
fn app_title(&self) -> String {
"IOTA".to_owned()
}
fn key_hints(&self) -> Vec<KeyHint> {
vec![
KeyHint {

View file

@ -13,12 +13,14 @@ use crate::{
interaction_result::InteractionResult,
render_context::RenderContext,
screens::screens::{AppAction, AppEvent, HitMap, KeyHint, Screen, UiEvent},
theme::{TerminalPolicy, ThemeName, UiConfig},
theme::{CliOutputFormat, TerminalPolicy, ThemeName, UiConfig},
};
#[derive(Clone, Copy, PartialEq, Eq)]
enum Focus {
Theme,
CliOutput,
CliConfirm,
RegenerateKeys,
Back,
}
@ -34,6 +36,8 @@ pub struct SettingsScreen {
message: String,
color: TerminalPolicy,
unicode: TerminalPolicy,
cli_output: CliOutputFormat,
cli_require_confirmation: bool,
focus: Focus,
dialog: Option<Dialog>,
pending: bool,
@ -45,16 +49,15 @@ impl SettingsScreen {
.iter()
.position(|theme| *theme == current)
.unwrap_or(0);
let config = UiConfig::load_or_default();
Self {
selected,
saved: current,
message: "Left/Right previews. Enter saves.".into(),
color: UiConfig::load()
.map(|config| config.color)
.unwrap_or_default(),
unicode: UiConfig::load()
.map(|config| config.unicode)
.unwrap_or_default(),
color: config.color,
unicode: config.unicode,
cli_output: config.cli_output,
cli_require_confirmation: config.cli_require_confirmation,
focus: Focus::Theme,
dialog: None,
pending: false,
@ -82,7 +85,9 @@ impl SettingsScreen {
fn next_focus(&mut self) {
self.focus = match self.focus {
Focus::Theme => Focus::RegenerateKeys,
Focus::Theme => Focus::CliOutput,
Focus::CliOutput => Focus::CliConfirm,
Focus::CliConfirm => Focus::RegenerateKeys,
Focus::RegenerateKeys => Focus::Back,
Focus::Back => Focus::Theme,
};
@ -92,7 +97,9 @@ impl SettingsScreen {
self.focus = match self.focus {
Focus::Theme => Focus::Back,
Focus::Back => Focus::RegenerateKeys,
Focus::RegenerateKeys => Focus::Theme,
Focus::RegenerateKeys => Focus::CliConfirm,
Focus::CliConfirm => Focus::CliOutput,
Focus::CliOutput => Focus::Theme,
};
}
@ -114,24 +121,44 @@ impl SettingsScreen {
match self.focus {
Focus::Theme => {
self.message = "Saving theme…".into();
let theme = self.selected_theme();
let color = self.color;
let unicode = self.unicode;
InteractionResult::AppTask {
task: Box::pin(async move {
UiEvent::App(AppEvent::SaveSettings {
theme,
color,
unicode,
})
}),
}
}
Focus::CliOutput => {
self.message = "Output format updated.".into();
return InteractionResult::Handled;
}
Focus::CliConfirm => {
self.cli_require_confirmation = !self.cli_require_confirmation;
self.message = format!(
"Confirm: {}",
if self.cli_require_confirmation {
"On"
} else {
"Off"
},
);
return InteractionResult::Handled;
}
Focus::RegenerateKeys => {
self.dialog = Some(Dialog::ConfirmRegenerateKeys);
InteractionResult::Handled
return InteractionResult::Handled;
}
Focus::Back => InteractionResult::CloseScreen,
Focus::Back => return InteractionResult::CloseScreen,
}
let theme = self.selected_theme();
let color = self.color;
let unicode = self.unicode;
let cli_output = self.cli_output;
let cli_require_confirmation = self.cli_require_confirmation;
InteractionResult::AppTask {
task: Box::pin(async move {
UiEvent::App(AppEvent::SaveSettings {
theme,
color,
unicode,
cli_output,
cli_require_confirmation,
})
}),
}
}
}
@ -152,13 +179,16 @@ impl Screen for SettingsScreen {
context: &RenderContext<'_>,
hits: &mut HitMap,
) {
let block = Block::default()
let header_block = Block::default()
.title(" Settings ")
.borders(Borders::ALL)
.border_style(context.theme.borders.focused);
let inner = block.inner(area);
frame.render_widget(block, area);
let rows = Layout::vertical([Constraint::Length(2), Constraint::Min(1)]).split(inner);
let inner = header_block.inner(area);
frame.render_widget(header_block, area);
let sections = Layout::vertical([Constraint::Length(2), Constraint::Min(1)])
.split(inner);
frame.render_widget(
Paragraph::new(format!(
"Theme: < {} >{}\nColor: {:?} (C) Unicode: {:?} (U)",
@ -169,18 +199,28 @@ impl Screen for SettingsScreen {
" [preview]"
},
self.color,
self.unicode
self.unicode,
))
.style(context.theme.text.heading),
rows[0],
sections[0],
);
let cli_line = format!(
"CLI output: {:?} (L) Confirm: {} (K)",
self.cli_output,
if self.cli_require_confirmation {
"required"
} else {
"disabled"
},
);
let bottom_rows =
Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(rows[1]);
Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).split(sections[1]);
let lines = vec![
Line::from(Span::styled(&self.message, context.theme.text.normal)),
Line::from(""),
Line::from(Span::styled(&cli_line, context.theme.text.normal)),
Line::from("Preview"),
Line::from("[OK] Healthy"),
Line::from("[WARN] Degraded"),
@ -352,6 +392,23 @@ impl Screen for SettingsScreen {
self.unicode = Self::next_policy(self.unicode);
InteractionResult::Handled
}
KeyCode::Char('l') | KeyCode::Char('L') => {
self.cli_output = self.cli_output.next();
self.message = format!("CLI output: {:?}", self.cli_output);
InteractionResult::Handled
}
KeyCode::Char('k') | KeyCode::Char('K') => {
self.cli_require_confirmation = !self.cli_require_confirmation;
self.message = format!(
"CLI confirm: {}",
if self.cli_require_confirmation {
"On"
} else {
"Off"
},
);
InteractionResult::Handled
}
KeyCode::Esc | KeyCode::Char('b') | KeyCode::Char('B') => {
InteractionResult::CloseScreen
}
@ -405,6 +462,10 @@ impl Screen for SettingsScreen {
keys: "C/U",
action: "Color/Unicode",
},
KeyHint {
keys: "L/K",
action: "CLI Out/Confirm",
},
KeyHint {
keys: "Esc/B",
action: "Back",

View file

@ -19,7 +19,7 @@ use std::{
any::Any,
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
atomic::{AtomicU8, AtomicUsize, Ordering},
},
};
@ -56,6 +56,7 @@ pub struct UsersScreen {
viewport_height: AtomicUsize,
filter: String,
filtering: bool,
tick: AtomicU8,
}
impl UsersScreen {
@ -74,6 +75,7 @@ impl UsersScreen {
viewport_height: AtomicUsize::new(1),
filter: String::new(),
filtering: false,
tick: AtomicU8::new(0),
}
}
@ -115,7 +117,12 @@ impl UsersScreen {
};
if self.loading {
f.render_widget(Paragraph::new("Loading users…"), inner);
const SPINNERS: &[u8] = b"|/-\\";
let ch = SPINNERS[self.tick.fetch_add(1, Ordering::Relaxed) as usize % SPINNERS.len()];
f.render_widget(
Paragraph::new(format!("{ch} Loading users…")),
inner,
);
return;
}
if visible_indices.is_empty() {

View file

@ -17,6 +17,55 @@ pub struct UiConfig {
pub color: TerminalPolicy,
#[serde(default)]
pub unicode: TerminalPolicy,
/// Default CLI output format for headless commands.
#[serde(default)]
pub cli_output: CliOutputFormat,
/// Whether destructive CLI operations require --yes by default.
#[serde(default = "default_false")]
pub cli_require_confirmation: bool,
}
fn default_false() -> bool {
false
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CliOutputFormat {
#[default]
Text,
Json,
Yaml,
Table,
}
impl CliOutputFormat {
pub fn all() -> &'static [CliOutputFormat] {
&[
CliOutputFormat::Text,
CliOutputFormat::Json,
CliOutputFormat::Yaml,
CliOutputFormat::Table,
]
}
pub fn name(&self) -> &'static str {
match self {
CliOutputFormat::Text => "text",
CliOutputFormat::Json => "json",
CliOutputFormat::Yaml => "yaml",
CliOutputFormat::Table => "table",
}
}
pub fn next(&self) -> Self {
match self {
CliOutputFormat::Text => CliOutputFormat::Json,
CliOutputFormat::Json => CliOutputFormat::Yaml,
CliOutputFormat::Yaml => CliOutputFormat::Table,
CliOutputFormat::Table => CliOutputFormat::Text,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@ -28,6 +77,16 @@ pub enum TerminalPolicy {
Never,
}
impl TerminalPolicy {
pub fn next(&self) -> Self {
match self {
TerminalPolicy::Auto => TerminalPolicy::Always,
TerminalPolicy::Always => TerminalPolicy::Never,
TerminalPolicy::Never => TerminalPolicy::Auto,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DaemonStartPolicy {
#[default]
@ -62,8 +121,21 @@ impl UiConfig {
pub fn path() -> PathBuf {
iota_paths::config_dir().join("ui.yaml")
}
fn fallback_path() -> Option<PathBuf> {
std::env::var_os("HOME")
.map(PathBuf::from)
.map(|d| d.join(".config").join("iota").join("ui.yaml"))
}
pub fn load() -> Result<Self, io::Error> {
Self::load_from(&Self::path())
let path = match (|| std::panic::catch_unwind(|| Self::path()))() {
Ok(path) => path,
Err(_) => Self::fallback_path().ok_or_else(|| {
io::Error::new(io::ErrorKind::NotFound, "could not determine config path")
})?,
};
Self::load_from(&path)
}
fn load_from(path: &Path) -> Result<Self, io::Error> {
@ -82,6 +154,12 @@ impl UiConfig {
fs::write(path, yaml)
}
/// Load from config path, or return defaults if the config path can't be resolved.
/// This avoids panics when `IOTA_SOCKET` is not set (e.g. in unit tests).
pub fn load_or_default() -> Self {
Self::load().unwrap_or_default()
}
pub fn resolve_theme(override_theme: Option<ThemeName>) -> ThemeName {
Self::resolve_theme_from(
override_theme,
@ -117,6 +195,33 @@ impl UiConfig {
}
}
}
/// Resolve the default CLI output format from config file and environment.
/// Priority: IOTA_OUTPUT env var > config file > "text" default.
pub fn resolve_cli_output(&self) -> CliOutputFormat {
if let Ok(value) = std::env::var("IOTA_OUTPUT") {
match value.to_ascii_lowercase().as_str() {
"json" => return CliOutputFormat::Json,
"yaml" | "yml" => return CliOutputFormat::Yaml,
"table" => return CliOutputFormat::Table,
_ => {}
}
}
self.cli_output
}
/// Resolve the default --yes behavior from config file and environment.
/// Priority: IOTA_YES env var > config file > false default.
pub fn resolve_cli_require_confirmation(&self) -> bool {
if let Ok(value) = std::env::var("IOTA_YES") {
match value.to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "y" => return false,
"0" | "false" | "no" | "n" => return true,
_ => {}
}
}
self.cli_require_confirmation
}
}
#[cfg(test)]
@ -173,4 +278,37 @@ mod tests {
ThemeName::Ansi
);
}
#[test]
fn cli_output_defaults_to_text() {
let config = UiConfig::default();
assert_eq!(config.resolve_cli_output(), CliOutputFormat::Text);
}
#[test]
fn cli_output_cycles_through_variants() {
assert_eq!(CliOutputFormat::Text.next(), CliOutputFormat::Json);
assert_eq!(CliOutputFormat::Json.next(), CliOutputFormat::Yaml);
assert_eq!(CliOutputFormat::Yaml.next(), CliOutputFormat::Table);
assert_eq!(CliOutputFormat::Table.next(), CliOutputFormat::Text);
}
#[test]
fn require_confirmation_defaults_to_false() {
let config = UiConfig::default();
assert!(!config.resolve_cli_require_confirmation());
}
#[test]
fn cli_output_serializes_roundtrip() {
let config = UiConfig {
cli_output: CliOutputFormat::Table,
cli_require_confirmation: true,
..Default::default()
};
let yaml = serde_yaml::to_string(&config).unwrap();
let loaded: UiConfig = serde_yaml::from_str(&yaml).unwrap();
assert_eq!(loaded.cli_output, CliOutputFormat::Table);
assert!(loaded.cli_require_confirmation);
}
}

View file

@ -3,7 +3,7 @@ mod model;
mod name;
mod presets;
pub use config::{DaemonStartPolicy, TerminalPolicy, UiConfig};
pub use config::{CliOutputFormat, DaemonStartPolicy, TerminalPolicy, UiConfig};
pub use model::*;
pub use name::ThemeName;

View file

@ -1,8 +1,10 @@
use crate::{
controls::header::render_header,
help_overlay::HelpOverlay,
input_handler::setup_input_handler,
interaction_result::InteractionResult,
ipc_client::IpcClient,
ipc_client::{DaemonStatus, IpcClient, IpcConnectionState},
notification::{Notification, render_notification_area},
render_context::RenderContext,
screens::{
main_screen::MainScreen,
@ -21,7 +23,7 @@ use once_cell::sync::Lazy;
use ratatui::{
Terminal,
backend::CrosstermBackend,
layout::{Constraint, Layout},
layout::{Constraint, Layout, Rect},
};
use std::{
io,
@ -53,6 +55,7 @@ pub struct UI {
app_event_tx: mpsc::UnboundedSender<UiEvent>,
app_event_rx: Mutex<Option<mpsc::UnboundedReceiver<UiEvent>>>,
header_focus: Mutex<Option<usize>>,
notifications: Arc<Mutex<Vec<Notification>>>,
}
pub fn start_tui(ipc: Arc<IpcClient>) -> io::Result<TuiSession> {
@ -237,6 +240,7 @@ impl UI {
app_event_tx,
app_event_rx: Mutex::new(Some(app_event_rx)),
header_focus: Mutex::new(None),
notifications: Arc::new(Mutex::new(Vec::new())),
})
}
@ -284,6 +288,27 @@ impl UI {
self.cancellation.clone()
}
pub async fn push_notification(&self, notification: Notification) {
if let Ok(mut notifications) = self.notifications.lock() {
notifications.push(notification);
self.invalidate();
}
}
pub async fn clear_expired_notifications(&self) {
if let Ok(mut notifications) = self.notifications.lock() {
let before = notifications.len();
notifications.retain(|n| !n.is_expired());
if notifications.len() != before {
self.invalidate();
}
}
}
pub async fn notifications(&self) -> Vec<Notification> {
self.notifications.lock().map(|n| n.clone()).unwrap_or_default()
}
pub async fn set_screen(&self, screen: Box<dyn Screen>) {
self.screen_stack.write().await.push(screen);
self.invalidate();
@ -332,6 +357,8 @@ impl UI {
theme,
color,
unicode,
cli_output,
cli_require_confirmation,
}) = &event
{
self.set_theme(theme::resolve(*theme)).await;
@ -339,6 +366,8 @@ impl UI {
config.theme = *theme;
config.color = *color;
config.unicode = *unicode;
config.cli_output = *cli_output;
config.cli_require_confirmation = *cli_require_confirmation;
let result = config
.save()
.map_err(|error| format!("Could not save UI settings: {error}"));
@ -385,6 +414,18 @@ impl UI {
self.invalidate();
return;
}
if key.code == KeyCode::Char('?') {
let has_help_overlay = self
.screen_stack
.read()
.await
.iter()
.any(|s| s.as_any().downcast_ref::<HelpOverlay>().is_some());
if !has_help_overlay {
self.set_screen(Box::new(HelpOverlay::new())).await;
}
return;
}
if header_is_focused {
let mut action = None;
if let Ok(mut focus) = self.header_focus.lock() {
@ -551,35 +592,61 @@ impl UI {
self.set_screen(Box::new(UsersScreen::loading(ipc.clone())))
.await;
let sender = self.app_event_tx.clone();
let ui = self.clone();
tokio::spawn(async move {
let result = match ipc.send_request(iota_ipc::LocalRequest::ListUsers).await {
Ok(iota_ipc::ResponseResult::Ok(iota_ipc::ResponsePayload::Users(users))) => {
Ok(users
.into_iter()
.map(|u| UserEntry {
user_id: u.user_id,
username: u.username,
})
.collect())
let load = async {
match ipc.send_request(iota_ipc::LocalRequest::ListUsers).await {
Ok(iota_ipc::ResponseResult::Ok(iota_ipc::ResponsePayload::Users(users))) => {
Ok(users
.into_iter()
.map(|u| UserEntry {
user_id: u.user_id,
username: u.username,
})
.collect())
}
Ok(iota_ipc::ResponseResult::Error(error)) => {
Err(format!("Cannot load users: {error}"))
}
Ok(_) => Err("Daemon returned an unexpected response while loading users.".into()),
Err(error) => Err(format!("Cannot load users: {error}")),
}
Ok(iota_ipc::ResponseResult::Error(error)) => {
Err(format!("Cannot load users: {error}"))
};
tokio::pin!(load);
let mut ticker = tokio::time::interval(std::time::Duration::from_millis(200));
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let result = loop {
tokio::select! {
result = &mut load => break result,
_ = ticker.tick() => {
ui.invalidate();
}
}
Ok(_) => Err("Daemon returned an unexpected response while loading users.".into()),
Err(error) => Err(format!("Cannot load users: {error}")),
};
let _ = sender.send(UiEvent::App(AppEvent::UsersLoaded(result)));
});
}
pub async fn render(&self) -> io::Result<()> {
self.clear_expired_notifications().await;
let theme = self.theme.read().await.clone();
let context = RenderContext {
theme: theme.as_ref(),
};
// The renderer is the only task that takes the terminal lock. Screen
// mutations use the stack lock briefly before invalidating a frame.
if let Some(screen) = self.screen_stack.read().await.last() {
let stack_guard = self.screen_stack.read().await;
let (connection, daemon) = stack_guard
.iter()
.find_map(|item| item.as_any().downcast_ref::<MainScreen>())
.map(|main| {
(
main.connection_status().borrow().clone(),
main.daemon_status().borrow().clone(),
)
})
.unwrap_or_else(|| (IpcConnectionState::Disconnected, DaemonStatus::default()));
if let Some(screen) = stack_guard.last() {
let mut terminal = self
.terminal
.lock()
@ -592,22 +659,12 @@ impl UI {
Constraint::Length(1),
])
.split(f.area());
let header_title = self
.screen_stack
.try_read()
.ok()
.and_then(|stack| {
stack
.iter()
.find_map(|item| item.as_any().downcast_ref::<MainScreen>())
.map(|main| main.app_title())
})
.unwrap_or_else(|| screen.app_title());
let header_focus = self.header_focus.lock().ok().and_then(|focus| *focus);
render_header(
f,
rows[0],
&header_title,
&connection,
&daemon,
context.theme,
&mut hits,
header_focus,
@ -615,12 +672,15 @@ impl UI {
let hints = if header_focus.is_some() {
" Left/Right: choose Enter: activate Esc/F6: screen".to_owned()
} else {
screen
let mut screen_hints: Vec<String> = screen
.key_hints()
.into_iter()
.map(|hint| format!("{}: {}", hint.keys, hint.action))
.collect::<Vec<_>>()
.join(" ")
.collect();
if !screen_hints.iter().any(|h| h.contains("?")) {
screen_hints.push("?: Help".to_owned());
}
screen_hints.join(" ")
};
f.render_widget(
ratatui::widgets::Paragraph::new(format!(" {hints}")).style(
@ -633,6 +693,18 @@ impl UI {
rows[2],
);
screen.render(f, rows[1], &context, &mut hits);
if let Ok(notifications) = self.notifications.try_lock() {
if !notifications.is_empty() {
let notification_area = Rect {
x: rows[1].x + rows[1].width.saturating_sub(40),
y: rows[1].y,
width: 40.min(rows[1].width),
height: 3.min(rows[1].height),
};
render_notification_area(f, notification_area, &notifications, context.theme);
}
}
})?;
if let Ok(mut current) = self.hits.lock() {
*current = hits;

View file

@ -44,7 +44,9 @@ async fn settings_preview_and_save_emit_typed_application_events() {
UiEvent::App(AppEvent::SaveSettings {
theme: ThemeName::Surface,
color: _,
unicode: _
unicode: _,
cli_output: _,
cli_require_confirmation: _
})
));
}