[Fix] Connection Management
This commit is contained in:
parent
9e9e3597da
commit
3f2ac18333
122 changed files with 19970 additions and 5263 deletions
|
|
@ -1,7 +0,0 @@
|
|||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ControlAction {
|
||||
FocusNext,
|
||||
FocusPrevious,
|
||||
Select,
|
||||
Activate,
|
||||
}
|
||||
|
|
@ -1,135 +0,0 @@
|
|||
use super::{choice::ChoiceVisualState, navigation::DisabledFocusPolicy};
|
||||
use std::{collections::HashSet, hash::Hash};
|
||||
|
||||
pub struct CheckboxItem<T> {
|
||||
pub value: T,
|
||||
pub label: String,
|
||||
pub description: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub disabled_reason: Option<String>,
|
||||
}
|
||||
pub struct CheckboxGroup<T: Clone + Eq + Hash> {
|
||||
items: Vec<CheckboxItem<T>>,
|
||||
selected: HashSet<T>,
|
||||
focused_index: usize,
|
||||
focus_policy: DisabledFocusPolicy,
|
||||
wrap_navigation: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CheckboxGroupError {
|
||||
Empty,
|
||||
DuplicateValue,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CheckboxChange<T> {
|
||||
Selected(T),
|
||||
Deselected(T),
|
||||
IgnoredDisabled(T),
|
||||
NoItem,
|
||||
}
|
||||
impl<T: Clone + Eq + Hash> CheckboxGroup<T> {
|
||||
pub fn new(
|
||||
items: Vec<CheckboxItem<T>>,
|
||||
selected: impl IntoIterator<Item = T>,
|
||||
) -> Result<Self, CheckboxGroupError> {
|
||||
let mut values = HashSet::new();
|
||||
if items.iter().any(|item| !values.insert(item.value.clone())) {
|
||||
return Err(CheckboxGroupError::DuplicateValue);
|
||||
}
|
||||
let selected = selected
|
||||
.into_iter()
|
||||
.filter(|value| values.contains(value))
|
||||
.collect();
|
||||
let focused_index = items.iter().position(|item| item.enabled).unwrap_or(0);
|
||||
Ok(Self {
|
||||
items,
|
||||
selected,
|
||||
focused_index,
|
||||
focus_policy: DisabledFocusPolicy::Skip,
|
||||
wrap_navigation: true,
|
||||
})
|
||||
}
|
||||
pub fn items(&self) -> &[CheckboxItem<T>] {
|
||||
&self.items
|
||||
}
|
||||
pub fn selected(&self) -> &HashSet<T> {
|
||||
&self.selected
|
||||
}
|
||||
pub fn focused_item(&self) -> Option<&CheckboxItem<T>> {
|
||||
self.items.get(self.focused_index)
|
||||
}
|
||||
pub fn set_focus_policy(&mut self, policy: DisabledFocusPolicy) {
|
||||
self.focus_policy = policy;
|
||||
}
|
||||
pub fn set_wrap_navigation(&mut self, wrap: bool) {
|
||||
self.wrap_navigation = wrap;
|
||||
}
|
||||
pub fn focus_next(&mut self) {
|
||||
self.move_focus(true);
|
||||
}
|
||||
pub fn focus_previous(&mut self) {
|
||||
self.move_focus(false);
|
||||
}
|
||||
fn move_focus(&mut self, forward: bool) {
|
||||
if self.items.is_empty() {
|
||||
return;
|
||||
}
|
||||
for step in 1..=self.items.len() {
|
||||
let current = self.focused_index as isize;
|
||||
let delta = if forward {
|
||||
step as isize
|
||||
} else {
|
||||
-(step as isize)
|
||||
};
|
||||
let raw = current + delta;
|
||||
let next = if self.wrap_navigation {
|
||||
raw.rem_euclid(self.items.len() as isize) as usize
|
||||
} else if raw < 0 || raw >= self.items.len() as isize {
|
||||
return;
|
||||
} else {
|
||||
raw as usize
|
||||
};
|
||||
if self.focus_policy == DisabledFocusPolicy::Include || self.items[next].enabled {
|
||||
self.focused_index = next;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn toggle_focused(&mut self) -> CheckboxChange<T> {
|
||||
let Some(item) = self.items.get(self.focused_index) else {
|
||||
return CheckboxChange::NoItem;
|
||||
};
|
||||
let value = item.value.clone();
|
||||
if !item.enabled {
|
||||
return CheckboxChange::IgnoredDisabled(value);
|
||||
}
|
||||
if self.selected.remove(&value) {
|
||||
CheckboxChange::Deselected(value)
|
||||
} else {
|
||||
self.selected.insert(value.clone());
|
||||
CheckboxChange::Selected(value)
|
||||
}
|
||||
}
|
||||
pub fn set_enabled(&mut self, value: &T, enabled: bool) {
|
||||
if let Some(item) = self.items.iter_mut().find(|item| &item.value == value) {
|
||||
item.enabled = enabled;
|
||||
}
|
||||
}
|
||||
pub fn set_selected(&mut self, value: T, selected: bool) {
|
||||
if selected {
|
||||
self.selected.insert(value);
|
||||
} else {
|
||||
self.selected.remove(&value);
|
||||
}
|
||||
}
|
||||
pub fn visual_state(&self, value: &T) -> ChoiceVisualState {
|
||||
let item = self.items.iter().position(|item| &item.value == value);
|
||||
ChoiceVisualState {
|
||||
selected: self.selected.contains(value),
|
||||
focused: item == Some(self.focused_index),
|
||||
enabled: item
|
||||
.and_then(|index| self.items.get(index))
|
||||
.is_some_and(|item| item.enabled),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
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",
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,7 @@ use crate::ipc_client::{DaemonStatus, IpcConnectionState};
|
|||
use crate::theme::ResolvedTheme;
|
||||
use crate::{
|
||||
controls::button::ButtonIntent,
|
||||
screens::screens::{AppAction, HitMap},
|
||||
screens::screens::{AppAction, HitMap, IotaMessage},
|
||||
};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
|
|
@ -119,7 +119,7 @@ pub fn render_header(
|
|||
Paragraph::new(vec![brand_line1, brand_line2]).style(theme.surfaces.toolbar),
|
||||
brand_area,
|
||||
);
|
||||
hits.register(brand_area, AppAction::OpenMain);
|
||||
hits.register(brand_area, IotaMessage::Action(AppAction::OpenMain));
|
||||
|
||||
for (index, item) in HEADER_ITEMS.iter().enumerate() {
|
||||
let top = cells[index + 1];
|
||||
|
|
@ -150,6 +150,6 @@ pub fn render_header(
|
|||
]),
|
||||
button_area,
|
||||
);
|
||||
hits.register(button_area, item.action);
|
||||
hits.register(button_area, IotaMessage::Action(item.action));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,119 +0,0 @@
|
|||
use crossterm::event::KeyCode;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MenuItem<T> {
|
||||
pub label: String,
|
||||
pub description: Option<String>,
|
||||
pub value: T,
|
||||
pub enabled: bool,
|
||||
pub disabled_reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MenuState<T> {
|
||||
items: Vec<MenuItem<T>>,
|
||||
selected: Option<usize>,
|
||||
}
|
||||
|
||||
impl<T> MenuState<T> {
|
||||
pub fn new(items: Vec<MenuItem<T>>) -> Self {
|
||||
let selected = items.iter().position(|item| item.enabled);
|
||||
Self { items, selected }
|
||||
}
|
||||
|
||||
pub fn items(&self) -> &[MenuItem<T>] {
|
||||
&self.items
|
||||
}
|
||||
pub fn selected_index(&self) -> Option<usize> {
|
||||
self.selected
|
||||
}
|
||||
pub fn selected_item(&self) -> Option<&MenuItem<T>> {
|
||||
self.selected.and_then(|index| self.items.get(index))
|
||||
}
|
||||
|
||||
pub fn move_next(&mut self) {
|
||||
self.move_by(1);
|
||||
}
|
||||
pub fn move_previous(&mut self) {
|
||||
self.move_by(-1);
|
||||
}
|
||||
pub fn first(&mut self) {
|
||||
self.selected = self.items.iter().position(|item| item.enabled);
|
||||
}
|
||||
pub fn last(&mut self) {
|
||||
self.selected = self.items.iter().rposition(|item| item.enabled);
|
||||
}
|
||||
|
||||
pub fn handle_key(&mut self, key: KeyCode) -> bool {
|
||||
match key {
|
||||
KeyCode::Up => self.move_previous(),
|
||||
KeyCode::Down => self.move_next(),
|
||||
KeyCode::Home => self.first(),
|
||||
KeyCode::End => self.last(),
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn move_by(&mut self, delta: isize) {
|
||||
let Some(current) = self.selected else {
|
||||
return;
|
||||
};
|
||||
for offset in 1..=self.items.len() {
|
||||
let next = (current as isize + delta * offset as isize)
|
||||
.rem_euclid(self.items.len() as isize) as usize;
|
||||
if self.items[next].enabled {
|
||||
self.selected = Some(next);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn navigation_skips_disabled_items() {
|
||||
let mut menu = MenuState::new(vec![
|
||||
MenuItem {
|
||||
label: "A".into(),
|
||||
description: None,
|
||||
value: 1,
|
||||
enabled: true,
|
||||
disabled_reason: None,
|
||||
},
|
||||
MenuItem {
|
||||
label: "B".into(),
|
||||
description: None,
|
||||
value: 2,
|
||||
enabled: false,
|
||||
disabled_reason: Some("Unavailable".into()),
|
||||
},
|
||||
MenuItem {
|
||||
label: "C".into(),
|
||||
description: None,
|
||||
value: 3,
|
||||
enabled: true,
|
||||
disabled_reason: None,
|
||||
},
|
||||
]);
|
||||
menu.move_next();
|
||||
assert_eq!(menu.selected_index(), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_enabled_set_is_safe() {
|
||||
let mut menu = MenuState::new(vec![MenuItem {
|
||||
label: "A".into(),
|
||||
description: None,
|
||||
value: (),
|
||||
enabled: false,
|
||||
disabled_reason: None,
|
||||
}]);
|
||||
menu.move_next();
|
||||
menu.last();
|
||||
assert_eq!(menu.selected_index(), None);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,12 +1,4 @@
|
|||
pub mod action;
|
||||
pub mod button;
|
||||
pub mod checkbox_group;
|
||||
pub mod choice;
|
||||
pub mod dialog;
|
||||
pub mod header;
|
||||
pub mod menu;
|
||||
pub mod navigation;
|
||||
pub mod panel;
|
||||
pub mod radio_group;
|
||||
pub mod scroll;
|
||||
pub mod text_input;
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum DisabledFocusPolicy {
|
||||
Include,
|
||||
#[default]
|
||||
Skip,
|
||||
}
|
||||
|
|
@ -1,194 +0,0 @@
|
|||
use super::{choice::ChoiceVisualState, navigation::DisabledFocusPolicy};
|
||||
|
||||
pub struct RadioItem<T> {
|
||||
pub value: T,
|
||||
pub label: String,
|
||||
pub description: Option<String>,
|
||||
pub enabled: bool,
|
||||
pub disabled_reason: Option<String>,
|
||||
}
|
||||
pub struct RadioGroup<T: Clone + Eq> {
|
||||
items: Vec<RadioItem<T>>,
|
||||
selected: T,
|
||||
default: T,
|
||||
focused_index: usize,
|
||||
focus_policy: DisabledFocusPolicy,
|
||||
wrap_navigation: bool,
|
||||
disabled_selection_policy: DisabledSelectionPolicy,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RadioGroupError {
|
||||
Empty,
|
||||
DefaultMissing,
|
||||
DefaultDisabled,
|
||||
NoEnabledItems,
|
||||
SelectedItemDisabled,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RadioChange<T> {
|
||||
Changed { previous: T, selected: T },
|
||||
Unchanged(T),
|
||||
IgnoredDisabled(T),
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DisabledSelectionPolicy {
|
||||
UseConfiguredDefault,
|
||||
UseFirstEnabled,
|
||||
ReturnError,
|
||||
}
|
||||
impl<T: Clone + Eq> RadioGroup<T> {
|
||||
pub fn new(
|
||||
items: Vec<RadioItem<T>>,
|
||||
observed: Option<T>,
|
||||
default: T,
|
||||
) -> Result<Self, RadioGroupError> {
|
||||
if items.is_empty() {
|
||||
return Err(RadioGroupError::Empty);
|
||||
}
|
||||
let default_item = items
|
||||
.iter()
|
||||
.find(|item| item.value == default)
|
||||
.ok_or(RadioGroupError::DefaultMissing)?;
|
||||
if !default_item.enabled {
|
||||
return Err(RadioGroupError::DefaultDisabled);
|
||||
}
|
||||
let focused_index = items
|
||||
.iter()
|
||||
.position(|item| item.enabled)
|
||||
.ok_or(RadioGroupError::NoEnabledItems)?;
|
||||
let selected = observed
|
||||
.filter(|value| {
|
||||
items
|
||||
.iter()
|
||||
.any(|item| item.enabled && item.value == *value)
|
||||
})
|
||||
.unwrap_or_else(|| default.clone());
|
||||
Ok(Self {
|
||||
items,
|
||||
selected,
|
||||
default,
|
||||
focused_index,
|
||||
focus_policy: DisabledFocusPolicy::Skip,
|
||||
wrap_navigation: true,
|
||||
disabled_selection_policy: DisabledSelectionPolicy::UseConfiguredDefault,
|
||||
})
|
||||
}
|
||||
pub fn items(&self) -> &[RadioItem<T>] {
|
||||
&self.items
|
||||
}
|
||||
pub fn selected(&self) -> &T {
|
||||
&self.selected
|
||||
}
|
||||
pub fn focused_item(&self) -> &RadioItem<T> {
|
||||
&self.items[self.focused_index]
|
||||
}
|
||||
pub fn focus_next(&mut self) {
|
||||
self.move_focus(true);
|
||||
}
|
||||
pub fn focus_previous(&mut self) {
|
||||
self.move_focus(false);
|
||||
}
|
||||
fn move_focus(&mut self, forward: bool) {
|
||||
for step in 1..=self.items.len() {
|
||||
let raw = self.focused_index as isize
|
||||
+ if forward {
|
||||
step as isize
|
||||
} else {
|
||||
-(step as isize)
|
||||
};
|
||||
let next = if self.wrap_navigation {
|
||||
raw.rem_euclid(self.items.len() as isize) as usize
|
||||
} else if raw < 0 || raw >= self.items.len() as isize {
|
||||
return;
|
||||
} else {
|
||||
raw as usize
|
||||
};
|
||||
if self.focus_policy == DisabledFocusPolicy::Include || self.items[next].enabled {
|
||||
self.focused_index = next;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn select_focused(&mut self) -> RadioChange<T> {
|
||||
let item = self.focused_item();
|
||||
let enabled = item.enabled;
|
||||
let value = item.value.clone();
|
||||
if !enabled {
|
||||
return RadioChange::IgnoredDisabled(value);
|
||||
}
|
||||
if value == self.selected {
|
||||
RadioChange::Unchanged(self.selected.clone())
|
||||
} else {
|
||||
let previous = std::mem::replace(&mut self.selected, value);
|
||||
RadioChange::Changed {
|
||||
previous,
|
||||
selected: self.selected.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn visual_state(&self, value: &T) -> ChoiceVisualState {
|
||||
let item = self.items.iter().position(|item| &item.value == value);
|
||||
ChoiceVisualState {
|
||||
selected: &self.selected == value,
|
||||
focused: item == Some(self.focused_index),
|
||||
enabled: item
|
||||
.and_then(|index| self.items.get(index))
|
||||
.is_some_and(|item| item.enabled),
|
||||
}
|
||||
}
|
||||
pub fn set_disabled_selection_policy(&mut self, policy: DisabledSelectionPolicy) {
|
||||
self.disabled_selection_policy = policy;
|
||||
}
|
||||
pub fn set_focus_policy(&mut self, policy: DisabledFocusPolicy) {
|
||||
self.focus_policy = policy;
|
||||
}
|
||||
pub fn set_wrap_navigation(&mut self, wrap: bool) {
|
||||
self.wrap_navigation = wrap;
|
||||
}
|
||||
pub fn set_enabled(&mut self, value: &T, enabled: bool) -> Result<(), RadioGroupError> {
|
||||
let Some(index) = self.items.iter().position(|item| &item.value == value) else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.items[index].enabled == enabled {
|
||||
return Ok(());
|
||||
}
|
||||
if !enabled
|
||||
&& self
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.all(|(other, item)| other == index || !item.enabled)
|
||||
{
|
||||
return Err(RadioGroupError::NoEnabledItems);
|
||||
}
|
||||
if !enabled && self.selected == *value {
|
||||
let replacement = match self.disabled_selection_policy {
|
||||
DisabledSelectionPolicy::UseConfiguredDefault if self.default != *value => self
|
||||
.items
|
||||
.iter()
|
||||
.find(|item| item.enabled && item.value == self.default)
|
||||
.map(|item| item.value.clone()),
|
||||
DisabledSelectionPolicy::UseConfiguredDefault => None,
|
||||
DisabledSelectionPolicy::UseFirstEnabled => self
|
||||
.items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(other, item)| *other != index && item.enabled)
|
||||
.map(|(_, item)| item.value.clone()),
|
||||
DisabledSelectionPolicy::ReturnError => {
|
||||
return Err(RadioGroupError::SelectedItemDisabled);
|
||||
}
|
||||
};
|
||||
self.selected = replacement.ok_or(RadioGroupError::SelectedItemDisabled)?;
|
||||
}
|
||||
self.items[index].enabled = enabled;
|
||||
if !enabled && self.focused_index == index && self.focus_policy == DisabledFocusPolicy::Skip
|
||||
{
|
||||
self.focus_next();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn default(&self) -> &T {
|
||||
&self.default
|
||||
}
|
||||
}
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
use ratatui::{
|
||||
Frame,
|
||||
layout::Rect,
|
||||
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
|
||||
};
|
||||
|
||||
/// Reusable viewport policy for long, vertically stacked terminal content.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ScrollOptions {
|
||||
pub show_scrollbar: bool,
|
||||
pub render_partial_components: bool,
|
||||
}
|
||||
impl Default for ScrollOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
show_scrollbar: true,
|
||||
render_partial_components: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ScrollField {
|
||||
pub offset: u16,
|
||||
pub options: ScrollOptions,
|
||||
}
|
||||
impl ScrollField {
|
||||
pub fn up(&mut self, amount: u16) {
|
||||
self.offset = self.offset.saturating_sub(amount);
|
||||
}
|
||||
pub fn down(&mut self, amount: u16, content_height: u16, viewport_height: u16) {
|
||||
self.offset = (self.offset.saturating_add(amount))
|
||||
.min(content_height.saturating_sub(viewport_height));
|
||||
}
|
||||
pub fn render(
|
||||
&self,
|
||||
frame: &mut Frame,
|
||||
area: Rect,
|
||||
content: Paragraph<'_>,
|
||||
content_height: u16,
|
||||
) {
|
||||
frame.render_widget(content.scroll((self.offset, 0)), area);
|
||||
if self.options.show_scrollbar && content_height > area.height {
|
||||
let mut state =
|
||||
ScrollbarState::new(content_height as usize).position(self.offset as usize);
|
||||
frame.render_stateful_widget(
|
||||
Scrollbar::new(ScrollbarOrientation::VerticalRight),
|
||||
area,
|
||||
&mut state,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,99 +0,0 @@
|
|||
use crossterm::event::KeyCode;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct TextInput {
|
||||
value: String,
|
||||
cursor: usize,
|
||||
label: Option<String>,
|
||||
placeholder: Option<String>,
|
||||
validation: Option<String>,
|
||||
secret: bool,
|
||||
}
|
||||
|
||||
impl TextInput {
|
||||
pub fn new(label: impl Into<String>) -> Self {
|
||||
Self {
|
||||
label: Some(label.into()),
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
pub fn value(&self) -> &str {
|
||||
&self.value
|
||||
}
|
||||
pub fn display_value(&self) -> String {
|
||||
if self.secret {
|
||||
"•".repeat(self.value.chars().count())
|
||||
} else {
|
||||
self.value.clone()
|
||||
}
|
||||
}
|
||||
pub fn set_placeholder(&mut self, value: impl Into<String>) {
|
||||
self.placeholder = Some(value.into());
|
||||
}
|
||||
pub fn placeholder(&self) -> Option<&str> {
|
||||
self.placeholder.as_deref()
|
||||
}
|
||||
pub fn label(&self) -> Option<&str> {
|
||||
self.label.as_deref()
|
||||
}
|
||||
pub fn validation(&self) -> Option<&str> {
|
||||
self.validation.as_deref()
|
||||
}
|
||||
pub fn set_validation(&mut self, value: Option<String>) {
|
||||
self.validation = value;
|
||||
}
|
||||
pub fn set_secret(&mut self, secret: bool) {
|
||||
self.secret = secret;
|
||||
}
|
||||
pub fn handle_key(&mut self, key: KeyCode) -> bool {
|
||||
match key {
|
||||
KeyCode::Backspace => {
|
||||
if self.cursor > 0 {
|
||||
let start = self.value[..self.cursor]
|
||||
.char_indices()
|
||||
.last()
|
||||
.map(|(index, _)| index)
|
||||
.unwrap_or(0);
|
||||
self.value.drain(start..self.cursor);
|
||||
self.cursor = start;
|
||||
}
|
||||
}
|
||||
KeyCode::Delete => {
|
||||
if self.cursor < self.value.len() {
|
||||
let end = self.value[self.cursor..]
|
||||
.char_indices()
|
||||
.nth(1)
|
||||
.map(|(index, _)| self.cursor + index)
|
||||
.unwrap_or(self.value.len());
|
||||
self.value.drain(self.cursor..end);
|
||||
}
|
||||
}
|
||||
KeyCode::Left => {
|
||||
if self.cursor > 0 {
|
||||
self.cursor = self.value[..self.cursor]
|
||||
.char_indices()
|
||||
.last()
|
||||
.map(|(index, _)| index)
|
||||
.unwrap_or(0);
|
||||
}
|
||||
}
|
||||
KeyCode::Right => {
|
||||
if self.cursor < self.value.len() {
|
||||
self.cursor = self.value[self.cursor..]
|
||||
.char_indices()
|
||||
.nth(1)
|
||||
.map(|(index, _)| self.cursor + index)
|
||||
.unwrap_or(self.value.len());
|
||||
}
|
||||
}
|
||||
KeyCode::Home => self.cursor = 0,
|
||||
KeyCode::End => self.cursor = self.value.len(),
|
||||
KeyCode::Char(character) => {
|
||||
self.value.insert(self.cursor, character);
|
||||
self.cursor += character.len_utf8();
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue