Compare commits

..

No commits in common. "4d32d4d403b72e6e55a3258ef8bc16d4dcdece51" and "f5066926fd3ff89569aa56c2b54b6991ad2dac97" have entirely different histories.

12 changed files with 138 additions and 875 deletions

View File

@ -5,7 +5,7 @@ use subxt::utils::H256;
use subxt::config::substrate::DigestItem; use subxt::config::substrate::DigestItem;
use crate::{ use crate::{
types::{ActionLevel, EraInfo, CasperExtrinsicDetails}, types::{EraInfo, CasperExtrinsicDetails},
}; };
use subxt::utils::AccountId32; use subxt::utils::AccountId32;
@ -28,14 +28,6 @@ pub enum Action {
UsedExplorerLog(Option<String>), UsedExplorerLog(Option<String>),
UsedAccount(AccountId32), UsedAccount(AccountId32),
NewAccount(String), NewAccount(String),
NewAddressBookRecord(String, String),
RenameAccount(String),
RenameAddressBookRecord(String),
UpdateAccountName(String),
UpdateAddressBookRecord(String),
WalletLog(String, ActionLevel),
NewBestBlock(u32), NewBestBlock(u32),
NewBestHash(H256), NewBestHash(H256),

View File

@ -104,7 +104,7 @@ impl Component for Explorer {
} }
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> { fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if !self.is_active { return Ok(None); } if self.is_active {
match key.code { match key.code {
KeyCode::Esc => { KeyCode::Esc => {
self.is_active = false; self.is_active = false;
@ -132,6 +132,7 @@ impl Component for Explorer {
} }
}, },
} }
}
Ok(None) Ok(None)
} }

View File

@ -26,7 +26,6 @@ use tokio::sync::mpsc::UnboundedSender;
use super::{PartialComponent, Component, CurrentTab}; use super::{PartialComponent, Component, CurrentTab};
use crate::casper::CasperConfig; use crate::casper::CasperConfig;
use crate::types::ActionLevel;
use crate::{ use crate::{
action::Action, action::Action,
config::Config, config::Config,
@ -69,45 +68,10 @@ impl Accounts {
let address = AccountId32::from(seed.clone()) let address = AccountId32::from(seed.clone())
.to_ss58check_with_version(Ss58AddressFormat::custom(1996)); .to_ss58check_with_version(Ss58AddressFormat::custom(1996));
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("new wallet '{}' with public address {} created", &name, &address),
ActionLevel::Info,
));
}
self.wallet_keys.push((name, address, secret_seed, pair_signer)); self.wallet_keys.push((name, address, secret_seed, pair_signer));
self.last_row();
self.save_to_file(); self.save_to_file();
} }
fn rename_account(&mut self, new_name: String) {
if let Some(index) = self.table_state.selected() {
let old_name = self.wallet_keys[index].0.clone();
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("wallet '{}' renamed to {}", &new_name, &old_name),
ActionLevel::Info,
));
}
self.wallet_keys[index].0 = new_name;
self.save_to_file();
}
}
fn update_account_name(&mut self) {
if let Some(index) = self.table_state.selected() {
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::RenameAccount(
self.wallet_keys[index].0.clone()
));
}
}
}
fn swap_up(&mut self) { fn swap_up(&mut self) {
if let Some(src_index) = self.table_state.selected() { if let Some(src_index) = self.table_state.selected() {
let dst_index = src_index.saturating_sub(1); let dst_index = src_index.saturating_sub(1);
@ -133,17 +97,9 @@ impl Accounts {
fn delete_row(&mut self) { fn delete_row(&mut self) {
if let Some(index) = self.table_state.selected() { if let Some(index) = self.table_state.selected() {
if self.wallet_keys.len() > 1 { if self.wallet_keys.len() > 1 {
let wallet = self.wallet_keys.remove(index); let _ = self.wallet_keys.remove(index);
self.previous_row(); self.previous_row();
self.save_to_file(); self.save_to_file();
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("wallet `{}` with public address {} removed",
&wallet.0, &wallet.1),
ActionLevel::Warn,
));
}
} }
} }
} }
@ -173,18 +129,11 @@ impl Accounts {
.expect("stored seed is valid length; qed"); .expect("stored seed is valid length; qed");
let pair = Pair::from_seed(&seed); let pair = Pair::from_seed(&seed);
let address = AccountId32::from(pair.public().0)
.to_ss58check_with_version(Ss58AddressFormat::custom(1996));
let pair_signer = PairSigner::<CasperConfig, Pair>::new(pair); let pair_signer = PairSigner::<CasperConfig, Pair>::new(pair);
let address = AccountId32::from(seed.clone())
.to_ss58check_with_version(Ss58AddressFormat::custom(1996));
self.wallet_keys.push((wallet_name.to_string(), address, wallet_key.to_string(), pair_signer)); self.wallet_keys.push((wallet_name.to_string(), address, wallet_key.to_string(), pair_signer));
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("read {} wallets from disk", self.wallet_keys.len()),
ActionLevel::Info,
));
}
} }
}, },
Err(_) => { Err(_) => {
@ -198,36 +147,24 @@ impl Accounts {
.try_into() .try_into()
.expect("stored seed is valid length; qed"); .expect("stored seed is valid length; qed");
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
"wallet read from the `/etc/ghost/wallet-key`".to_string(),
ActionLevel::Warn,
));
}
let pair = Pair::from_seed(&seed); let pair = Pair::from_seed(&seed);
(pair, seed) (pair, seed)
} }
Err(_) => { Err(_) => {
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
"no wallets found on disk, new wallet created".to_string(),
ActionLevel::Warn,
));
}
let (pair, seed) = Pair::generate(); let (pair, seed) = Pair::generate();
(pair, seed) (pair, seed)
} }
}; };
let secret_seed = hex::encode(seed); let secret_seed = hex::encode(seed);
let address = AccountId32::from(pair.public().0)
.to_ss58check_with_version(Ss58AddressFormat::custom(1996));
let pair_signer = PairSigner::<CasperConfig, Pair>::new(pair); let pair_signer = PairSigner::<CasperConfig, Pair>::new(pair);
let mut new_file = File::create(file_path)?; let mut new_file = File::create(file_path)?;
writeln!(new_file, "ghostie:0x{}", &secret_seed)?; writeln!(new_file, "ghostie:0x{}", &secret_seed)?;
let address = AccountId32::from(seed.clone())
.to_ss58check_with_version(Ss58AddressFormat::custom(1996));
self.wallet_keys.push(("ghostie".to_string(), address, secret_seed, pair_signer)); self.wallet_keys.push(("ghostie".to_string(), address, secret_seed, pair_signer));
} }
}; };
@ -294,7 +231,11 @@ impl PartialComponent for Accounts {
fn set_active(&mut self, current_tab: CurrentTab) { fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab { match current_tab {
CurrentTab::Accounts => self.is_active = true, CurrentTab::Accounts => self.is_active = true,
_ => self.is_active = false, _ => {
self.is_active = false;
self.table_state.select(None);
self.scroll_state = self.scroll_state.position(0);
}
} }
} }
} }
@ -328,7 +269,6 @@ impl Component for Accounts {
fn update(&mut self, action: Action) -> Result<Option<Action>> { fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action { match action {
Action::NewAccount(name) => self.create_new_account(name), Action::NewAccount(name) => self.create_new_account(name),
Action::UpdateAccountName(new_name) => self.rename_account(new_name),
_ => {} _ => {}
}; };
Ok(None) Ok(None)
@ -343,7 +283,6 @@ impl Component for Accounts {
KeyCode::Char('g') if self.is_active => self.first_row(), KeyCode::Char('g') if self.is_active => self.first_row(),
KeyCode::Char('G') if self.is_active => self.last_row(), KeyCode::Char('G') if self.is_active => self.last_row(),
KeyCode::Char('D') if self.is_active => self.delete_row(), KeyCode::Char('D') if self.is_active => self.delete_row(),
KeyCode::Char('R') if self.is_active => self.update_account_name(),
_ => {}, _ => {},
}; };
Ok(None) Ok(None)
@ -362,8 +301,8 @@ impl Component for Accounts {
Cell::from(Text::from("31 CSPR".to_string()).alignment(Alignment::Right)), Cell::from(Text::from("31 CSPR".to_string()).alignment(Alignment::Right)),
])), ])),
[ [
Constraint::Min(5), Constraint::Min(0),
Constraint::Max(51), Constraint::Min(15),
Constraint::Min(10), Constraint::Min(10),
], ],
) )

View File

@ -68,11 +68,8 @@ impl PartialComponent for AddAccount {
fn set_active(&mut self, current_tab: CurrentTab) { fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab { match current_tab {
CurrentTab::AddAccount => self.is_active = true, CurrentTab::AddAccount => self.is_active = true,
_ => { _ => self.is_active = false,
self.is_active = false; }
self.name = Input::new(String::new());
},
};
} }
} }
@ -92,7 +89,7 @@ impl Component for AddAccount {
} }
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> { fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if self.is_active && key.kind == KeyEventKind::Press { if key.kind == KeyEventKind::Press {
match key.code { match key.code {
KeyCode::Enter => self.submit_message(), KeyCode::Enter => self.submit_message(),
KeyCode::Char(to_insert) => self.enter_char(to_insert), KeyCode::Char(to_insert) => self.enter_char(to_insert),

View File

@ -1,202 +0,0 @@
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind};
use color_eyre::Result;
use ratatui::{
layout::{Position, Alignment, Constraint, Flex, Layout, Rect},
widgets::{Block, Clear, Paragraph},
Frame
};
use tokio::sync::mpsc::UnboundedSender;
use super::{Component, PartialComponent, CurrentTab};
use crate::{
widgets::{Input, InputRequest},
action::Action,
config::Config,
palette::StylePalette,
};
#[derive(Debug)]
enum NameOrAddress {
Name,
Address,
}
#[derive(Debug)]
pub struct AddAddressBookRecord {
is_active: bool,
name_or_address: NameOrAddress,
action_tx: Option<UnboundedSender<Action>>,
name: Input,
address: Input,
palette: StylePalette
}
impl Default for AddAddressBookRecord {
fn default() -> Self {
Self::new()
}
}
impl AddAddressBookRecord {
pub fn new() -> Self {
Self {
is_active: false,
name_or_address: NameOrAddress::Name,
action_tx: None,
name: Input::new(String::new()),
address: Input::new(String::new()),
palette: StylePalette::default(),
}
}
}
impl AddAddressBookRecord {
fn submit_message(&mut self) {
match self.name_or_address {
NameOrAddress::Name => self.name_or_address = NameOrAddress::Address,
NameOrAddress::Address => if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::NewAddressBookRecord(
self.name.value().to_string(),
self.address.value().to_string()));
}
}
}
fn enter_char(&mut self, new_char: char) {
match self.name_or_address {
NameOrAddress::Name => {
let _ = self.name.handle(InputRequest::InsertChar(new_char));
},
NameOrAddress::Address => {
let _ = self.address.handle(InputRequest::InsertChar(new_char));
}
}
}
fn delete_char(&mut self) {
match self.name_or_address {
NameOrAddress::Name => {
let _ = self.name.handle(InputRequest::DeletePrevChar);
},
NameOrAddress::Address => {
let _ = self.address.handle(InputRequest::DeletePrevChar);
}
}
}
fn move_cursor_right(&mut self) {
match self.name_or_address {
NameOrAddress::Name => {
let _ = self.name.handle(InputRequest::GoToNextChar);
},
NameOrAddress::Address => {
let _ = self.address.handle(InputRequest::GoToNextChar);
}
}
}
fn move_cursor_left(&mut self) {
match self.name_or_address {
NameOrAddress::Name => {
let _ = self.name.handle(InputRequest::GoToPrevChar);
},
NameOrAddress::Address => {
let _ = self.address.handle(InputRequest::GoToPrevChar);
}
}
}
}
impl PartialComponent for AddAddressBookRecord {
fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab {
CurrentTab::AddAddressBookRecord => self.is_active = true,
_ => {
self.is_active = false;
self.name = Input::new(String::new());
self.address = Input::new(String::new());
self.name_or_address = NameOrAddress::Name;
},
};
}
}
impl Component for AddAddressBookRecord {
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
self.action_tx = Some(tx);
Ok(())
}
fn register_config_handler(&mut self, config: Config) -> Result<()> {
if let Some(style) = config.styles.get(&crate::app::Mode::Explorer) {
self.palette.with_normal_style(style.get("normal_style").copied());
self.palette.with_normal_border_style(style.get("normal_border_style").copied());
self.palette.with_normal_title_style(style.get("normal_title_style").copied());
}
Ok(())
}
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if self.is_active && key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Up => self.name_or_address = NameOrAddress::Name,
KeyCode::Down => self.name_or_address = NameOrAddress::Address,
KeyCode::Enter => self.submit_message(),
KeyCode::Char(to_insert) => self.enter_char(to_insert),
KeyCode::Backspace => self.delete_char(),
KeyCode::Left => self.move_cursor_left(),
KeyCode::Right => self.move_cursor_right(),
KeyCode::Esc => self.is_active = false,
_ => {},
};
}
Ok(None)
}
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
if self.is_active {
let size = area.as_size();
let name_area = Rect::new(size.width / 2, size.height / 2, 50, 3);
let address_area = Rect::new(size.width / 2, size.height / 2 + 3, 50, 3);
let input_name = Paragraph::new(self.name.value())
.block(Block::bordered()
.title_alignment(Alignment::Right)
.title("New name in Address Book"));
let input_address = Paragraph::new(self.address.value())
.block(Block::bordered()
.title_alignment(Alignment::Right)
.title("Address for new name"));
let v = Layout::vertical([Constraint::Max(3)]).flex(Flex::Center);
let h = Layout::horizontal([Constraint::Max(50)]).flex(Flex::Center);
let [name_area] = v.areas(name_area);
let [name_area] = h.areas(name_area);
let [address_area] = v.areas(address_area);
let [address_area] = h.areas(address_area);
frame.render_widget(Clear, name_area);
frame.render_widget(Clear, address_area);
frame.render_widget(input_name, name_area);
frame.render_widget(input_address, address_area);
match self.name_or_address {
NameOrAddress::Name => {
frame.set_cursor_position(Position::new(
name_area.x + self.name.cursor() as u16 + 1,
name_area.y + 1
));
},
NameOrAddress::Address => {
frame.set_cursor_position(Position::new(
address_area.x + self.address.cursor() as u16 + 1,
address_area.y + 1
));
}
}
}
Ok(())
}
}

View File

@ -12,11 +12,9 @@ use ratatui::{
widgets::{Block, ScrollbarState, Row, Table, TableState}, widgets::{Block, ScrollbarState, Row, Table, TableState},
Frame Frame
}; };
use subxt::ext::sp_core::crypto::{ByteArray, Ss58Codec, Ss58AddressFormat, AccountId32}; use subxt::ext::sp_core::crypto::{Ss58Codec, Ss58AddressFormat, AccountId32};
use tokio::sync::mpsc::UnboundedSender;
use super::{Component, PartialComponent, CurrentTab}; use super::{Component, PartialComponent, CurrentTab};
use crate::types::ActionLevel;
use crate::{ use crate::{
action::Action, action::Action,
config::Config, config::Config,
@ -25,7 +23,6 @@ use crate::{
pub struct AddressBook { pub struct AddressBook {
is_active: bool, is_active: bool,
action_tx: Option<UnboundedSender<Action>>,
address_book_file: PathBuf, address_book_file: PathBuf,
address_book: Vec<(String, String, AccountId32, String)>, address_book: Vec<(String, String, AccountId32, String)>,
scroll_state: ScrollbarState, scroll_state: ScrollbarState,
@ -43,7 +40,6 @@ impl AddressBook {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
is_active: false, is_active: false,
action_tx: None,
address_book_file: Default::default(), address_book_file: Default::default(),
address_book: Vec::new(), address_book: Vec::new(),
scroll_state: ScrollbarState::new(0), scroll_state: ScrollbarState::new(0),
@ -80,13 +76,6 @@ impl AddressBook {
let address = AccountId32::from(seed.clone()) let address = AccountId32::from(seed.clone())
.to_ss58check_with_version(Ss58AddressFormat::custom(1996)); .to_ss58check_with_version(Ss58AddressFormat::custom(1996));
self.address_book.push((name.to_string(), address, account_id, seed_str.to_string())); self.address_book.push((name.to_string(), address, account_id, seed_str.to_string()));
}
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("read {} records from address book", self.address_book.len()),
ActionLevel::Info,
));
} }
}, },
Err(_) => { Err(_) => {
@ -119,77 +108,12 @@ impl AddressBook {
.to_ss58check_with_version(Ss58AddressFormat::custom(1996)); .to_ss58check_with_version(Ss58AddressFormat::custom(1996));
self.address_book.push((chad_info.0.to_string(), address, chad_account_id, chad_info.1.to_string())); self.address_book.push((chad_info.0.to_string(), address, chad_account_id, chad_info.1.to_string()));
}); });
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("address book is empty, filling it with giga chad boyz as default"),
ActionLevel::Warn,
));
}
} }
}; };
self.scroll_state = self.scroll_state.content_length(self.address_book.len()); self.scroll_state = self.scroll_state.content_length(self.address_book.len());
Ok(()) Ok(())
} }
fn rename_record(&mut self, new_name: String) {
if let Some(index) = self.table_state.selected() {
let old_name = self.address_book[index].0.clone();
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("record renamed from {} to {}", &old_name, &new_name),
ActionLevel::Info,
));
}
self.address_book[index].0 = new_name;
self.save_to_file();
}
}
fn add_new_record(&mut self, name: String, address: String) {
match AccountId32::from_ss58check_with_version(&address) {
Ok((account_id, format)) => {
if format != Ss58AddressFormat::custom(1996) {
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("provided public address for {} is not part of Casper/Ghost ecosystem", &address),
ActionLevel::Error,
));
}
}
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("account {} with address {} added to address book", &name, &address),
ActionLevel::Info,
));
}
let seed_vec = account_id.to_raw_vec();
let seed_str = hex::encode(seed_vec);
self.address_book.push((name, address, account_id, seed_str));
self.save_to_file();
self.last_row();
},
Err(_) => if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::WalletLog(
format!("provided account address {} is invalid", &address),
ActionLevel::Error,
));
}
}
}
fn update_address_book_record(&mut self) {
if let Some(index) = self.table_state.selected() {
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::RenameAddressBookRecord(
self.address_book[index].0.clone()
));
}
}
}
fn swap_up(&mut self) { fn swap_up(&mut self) {
if let Some(src_index) = self.table_state.selected() { if let Some(src_index) = self.table_state.selected() {
let dst_index = src_index.saturating_sub(1); let dst_index = src_index.saturating_sub(1);
@ -270,7 +194,11 @@ impl PartialComponent for AddressBook {
fn set_active(&mut self, current_tab: CurrentTab) { fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab { match current_tab {
CurrentTab::AddressBook => self.is_active = true, CurrentTab::AddressBook => self.is_active = true,
_ => self.is_active = false, _ => {
self.is_active = false;
self.table_state.select(None);
self.scroll_state = self.scroll_state.position(0);
}
} }
} }
} }
@ -295,23 +223,6 @@ impl Component for AddressBook {
Ok(()) Ok(())
} }
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
self.action_tx = Some(tx);
Ok(())
}
fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::UpdateAddressBookRecord(new_name) =>
self.rename_record(new_name),
Action::NewAddressBookRecord(name, address) =>
self.add_new_record(name, address),
_ => {}
};
Ok(None)
}
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> { fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
match key.code { match key.code {
KeyCode::Up | KeyCode::Char('k') if self.is_active => self.previous_row(), KeyCode::Up | KeyCode::Char('k') if self.is_active => self.previous_row(),
@ -321,7 +232,6 @@ impl Component for AddressBook {
KeyCode::Char('K') if self.is_active => self.swap_up(), KeyCode::Char('K') if self.is_active => self.swap_up(),
KeyCode::Char('J') if self.is_active => self.swap_down(), KeyCode::Char('J') if self.is_active => self.swap_down(),
KeyCode::Char('D') if self.is_active => self.delete_row(), KeyCode::Char('D') if self.is_active => self.delete_row(),
KeyCode::Char('R') if self.is_active => self.update_address_book_record(),
_ => {}, _ => {},
}; };
Ok(None) Ok(None)
@ -340,8 +250,8 @@ impl Component for AddressBook {
Cell::from(Text::from("31 CSPR".to_string()).alignment(Alignment::Right)), Cell::from(Text::from("31 CSPR".to_string()).alignment(Alignment::Right)),
])), ])),
[ [
Constraint::Min(5), Constraint::Min(0),
Constraint::Max(51), Constraint::Min(13),
Constraint::Min(10), Constraint::Min(10),
], ],
) )

View File

@ -1,65 +1,38 @@
use color_eyre::Result; use color_eyre::Result;
use ratatui::{ use ratatui::{
layout::{Alignment, Constraint, Margin, Rect}, layout::{Alignment, Rect},
style::{Color, Style}, widgets::{Block, Paragraph, Wrap},
text::Text,
widgets::{
Block, Padding, Cell, Row, Scrollbar, ScrollbarOrientation,
ScrollbarState, Table, TableState,
},
Frame Frame
}; };
use super::{Component, PartialComponent, CurrentTab}; use super::{Component, PartialComponent, CurrentTab};
use crate::{ use crate::{
types::ActionLevel,
action::Action, action::Action,
config::Config, config::Config,
palette::StylePalette, palette::StylePalette,
}; };
#[derive(Debug, Default)] #[derive(Debug)]
struct WalletLog {
time: chrono::DateTime<chrono::Local>,
level: ActionLevel,
message: String,
}
#[derive(Debug, Default)]
pub struct EventLogs { pub struct EventLogs {
is_active: bool,
scroll_state: ScrollbarState,
table_state: TableState,
logs: std::collections::VecDeque<WalletLog>,
palette: StylePalette palette: StylePalette
} }
impl EventLogs { impl Default for EventLogs {
const MAX_LOGS: usize = 50; fn default() -> Self {
Self::new()
fn add_new_log(&mut self, message: String, level: ActionLevel) {
self.logs.push_back(WalletLog {
time: chrono::Local::now(),
level,
message,
});
if self.logs.len() > Self::MAX_LOGS {
let _ = self.logs.pop_front();
} }
}
self.table_state.select(Some(self.logs.len() - 1)); impl EventLogs {
self.scroll_state = self.scroll_state.content_length(self.logs.len()); pub fn new() -> Self {
Self {
palette: StylePalette::default(),
}
} }
} }
impl PartialComponent for EventLogs { impl PartialComponent for EventLogs {
fn set_active(&mut self, current_tab: CurrentTab) { fn set_active(&mut self, _current_tab: CurrentTab) {}
match current_tab {
CurrentTab::EventLogs => self.is_active = true,
_ => self.is_active = false,
}
}
} }
impl Component for EventLogs { impl Component for EventLogs {
@ -77,7 +50,6 @@ impl Component for EventLogs {
fn update(&mut self, action: Action) -> Result<Option<Action>> { fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action { match action {
Action::WalletLog(message, level) => self.add_new_log(message, level),
_ => {} _ => {}
}; };
Ok(None) Ok(None)
@ -86,51 +58,18 @@ impl Component for EventLogs {
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> { fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
let [_, place] = super::wallet_layout(area); let [_, place] = super::wallet_layout(area);
let (border_style, border_type) = self.palette.create_border_style(self.is_active); let (border_style, border_type) = self.palette.create_border_style(false);
let error_style = Style::new().fg(Color::Red); let paragraph = Paragraph::new("latest logs")
let warn_style = Style::new().fg(Color::Yellow);
let info_style = Style::new().fg(Color::Green);
let table = Table::new(
self.logs
.iter()
.map(|log| {
let style = match log.level {
ActionLevel::Info => info_style,
ActionLevel::Warn => warn_style,
ActionLevel::Error => error_style,
};
Row::new(vec![
Cell::from(Text::from(log.time.format("%H:%M:%S").to_string()).style(style).alignment(Alignment::Left)),
Cell::from(Text::from(log.message.clone()).style(style).alignment(Alignment::Left)),
])
}),
[
Constraint::Max(8),
Constraint::Min(0),
],
)
.column_spacing(1)
.block(Block::bordered() .block(Block::bordered()
.border_style(border_style) .border_style(border_style)
.border_type(border_type) .border_type(border_type)
.padding(Padding::right(2))
.title_alignment(Alignment::Right) .title_alignment(Alignment::Right)
.title_style(self.palette.create_title_style(false)) .title_style(self.palette.create_title_style(false))
.title("Action Logs")); .title("Latest Logs"))
.alignment(Alignment::Center)
.wrap(Wrap { trim: true });
let scrollbar = Scrollbar::default() frame.render_widget(paragraph, place);
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(None)
.end_symbol(None)
.style(self.palette.create_scrollbar_style());
frame.render_stateful_widget(table, place, &mut self.table_state);
frame.render_stateful_widget(
scrollbar,
place.inner(Margin { vertical: 1, horizontal: 1 }),
&mut self.scroll_state,
);
Ok(()) Ok(())
} }
} }

View File

@ -9,24 +9,18 @@ mod balance;
mod transfer; mod transfer;
mod address_book; mod address_book;
mod add_account; mod add_account;
mod rename_account;
mod event_logs; mod event_logs;
mod accounts; mod accounts;
mod overview; mod overview;
mod add_address_book_record;
mod rename_address_book_record;
use balance::Balance; use balance::Balance;
use tokio::sync::mpsc::UnboundedSender; use tokio::sync::mpsc::UnboundedSender;
use transfer::Transfer; use transfer::Transfer;
use address_book::AddressBook; use address_book::AddressBook;
use add_account::AddAccount; use add_account::AddAccount;
use rename_account::RenameAccount;
use event_logs::EventLogs; use event_logs::EventLogs;
use accounts::Accounts; use accounts::Accounts;
use overview::Overview; use overview::Overview;
use add_address_book_record::AddAddressBookRecord;
use rename_address_book_record::RenameAddressBookRecord;
use super::Component; use super::Component;
use crate::{action::Action, app::Mode, config::Config}; use crate::{action::Action, app::Mode, config::Config};
@ -36,11 +30,7 @@ pub enum CurrentTab {
Nothing, Nothing,
Accounts, Accounts,
AddressBook, AddressBook,
EventLogs,
AddAccount, AddAccount,
AddAddressBookRecord,
RenameAccount,
RenameAddressBookRecord,
} }
pub trait PartialComponent: Component { pub trait PartialComponent: Component {
@ -66,9 +56,6 @@ impl Default for Wallet {
Box::new(EventLogs::default()), Box::new(EventLogs::default()),
Box::new(Transfer::default()), Box::new(Transfer::default()),
Box::new(AddAccount::default()), Box::new(AddAccount::default()),
Box::new(RenameAccount::default()),
Box::new(AddAddressBookRecord::default()),
Box::new(RenameAddressBookRecord::default()),
], ],
} }
} }
@ -76,10 +63,8 @@ impl Default for Wallet {
impl Wallet { impl Wallet {
fn move_left(&mut self) { fn move_left(&mut self) {
match self.current_tab { if let CurrentTab::AddressBook = self.current_tab {
CurrentTab::EventLogs => self.current_tab = CurrentTab::AddressBook, self.current_tab = CurrentTab::Accounts;
CurrentTab::AddressBook => self.current_tab = CurrentTab::Accounts,
_ => {}
} }
} }
@ -87,12 +72,15 @@ impl Wallet {
match self.current_tab { match self.current_tab {
CurrentTab::Nothing => self.current_tab = CurrentTab::Accounts, CurrentTab::Nothing => self.current_tab = CurrentTab::Accounts,
CurrentTab::Accounts => self.current_tab = CurrentTab::AddressBook, CurrentTab::Accounts => self.current_tab = CurrentTab::AddressBook,
CurrentTab::AddressBook => self.current_tab = CurrentTab::EventLogs,
_ => {} _ => {}
} }
} }
} }
impl PartialComponent for Wallet {
fn set_active(&mut self, _current_tab: CurrentTab) {}
}
impl Component for Wallet { impl Component for Wallet {
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> { fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
for component in self.components.iter_mut() { for component in self.components.iter_mut() {
@ -111,14 +99,9 @@ impl Component for Wallet {
} }
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> { fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if !self.is_active { return Ok(None) } if self.is_active {
if self.current_tab == CurrentTab::AddAccount {
match self.current_tab { match key.code {
// block the default key handle for popups
CurrentTab::AddAccount |
CurrentTab::RenameAccount |
CurrentTab::RenameAddressBookRecord |
CurrentTab::AddAddressBookRecord => match key.code {
KeyCode::Esc => { KeyCode::Esc => {
self.current_tab = CurrentTab::Accounts; self.current_tab = CurrentTab::Accounts;
for component in self.components.iter_mut() { for component in self.components.iter_mut() {
@ -130,8 +113,9 @@ impl Component for Wallet {
component.handle_key_event(key)?; component.handle_key_event(key)?;
} }
} }
}, }
_ => match key.code { } else {
match key.code {
KeyCode::Esc => { KeyCode::Esc => {
self.is_active = false; self.is_active = false;
self.current_tab = CurrentTab::Nothing; self.current_tab = CurrentTab::Nothing;
@ -140,18 +124,12 @@ impl Component for Wallet {
} }
return Ok(Some(Action::SetActiveScreen(Mode::Menu))); return Ok(Some(Action::SetActiveScreen(Mode::Menu)));
}, },
KeyCode::Char('W') => { KeyCode::Char('w') => {
self.current_tab = CurrentTab::AddAccount; self.current_tab = CurrentTab::AddAccount;
for component in self.components.iter_mut() { for component in self.components.iter_mut() {
component.set_active(self.current_tab.clone()); component.set_active(self.current_tab.clone());
} }
}, },
KeyCode::Char('A') => {
self.current_tab = CurrentTab::AddAddressBookRecord;
for component in self.components.iter_mut() {
component.set_active(self.current_tab.clone());
}
},
KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => { KeyCode::Enter | KeyCode::Char('l') | KeyCode::Right => {
self.move_right(); self.move_right();
for component in self.components.iter_mut() { for component in self.components.iter_mut() {
@ -171,23 +149,25 @@ impl Component for Wallet {
}, },
} }
} }
}
Ok(None) Ok(None)
} }
fn update(&mut self, action: Action) -> Result<Option<Action>> { fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action { if let Action::SetActiveScreen(Mode::Wallet) = action {
Action::SetActiveScreen(Mode::Wallet) => self.is_active = true, self.is_active = true;
Action::UpdateAccountName(_) | Action::NewAccount(_) => self.current_tab = CurrentTab::Accounts;
self.current_tab = CurrentTab::Accounts,
Action::UpdateAddressBookRecord(_) | Action::NewAddressBookRecord(_, _) =>
self.current_tab = CurrentTab::AddressBook,
Action::RenameAccount(_) => self.current_tab = CurrentTab::RenameAccount,
Action::RenameAddressBookRecord(_) =>
self.current_tab = CurrentTab::RenameAddressBookRecord,
_ => {}
}
for component in self.components.iter_mut() { for component in self.components.iter_mut() {
component.set_active(self.current_tab.clone()); component.set_active(self.current_tab.clone());
}
}
if let Action::NewAccount(_) = action {
self.current_tab = CurrentTab::Accounts;
for component in self.components.iter_mut() {
component.set_active(self.current_tab.clone());
}
}
for component in self.components.iter_mut() {
component.update(action.clone())?; component.update(action.clone())?;
} }
Ok(None) Ok(None)

View File

@ -1,140 +0,0 @@
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind};
use color_eyre::Result;
use ratatui::{
layout::{Position, Alignment, Constraint, Flex, Layout, Rect},
widgets::{Block, Clear, Paragraph},
Frame
};
use tokio::sync::mpsc::UnboundedSender;
use super::{Component, PartialComponent, CurrentTab};
use crate::{
widgets::{Input, InputRequest},
action::Action,
config::Config,
palette::StylePalette,
};
#[derive(Debug)]
pub struct RenameAccount {
is_active: bool,
action_tx: Option<UnboundedSender<Action>>,
old_name: String,
name: Input,
palette: StylePalette
}
impl Default for RenameAccount {
fn default() -> Self {
Self::new()
}
}
impl RenameAccount {
pub fn new() -> Self {
Self {
is_active: false,
old_name: String::new(),
action_tx: None,
name: Input::new(String::new()),
palette: StylePalette::default(),
}
}
}
impl RenameAccount {
fn submit_message(&mut self) {
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::UpdateAccountName(self.name.value().to_string()));
}
}
fn enter_char(&mut self, new_char: char) {
let _ = self.name.handle(InputRequest::InsertChar(new_char));
}
fn delete_char(&mut self) {
let _ = self.name.handle(InputRequest::DeletePrevChar);
}
fn move_cursor_right(&mut self) {
let _ = self.name.handle(InputRequest::GoToNextChar);
}
fn move_cursor_left(&mut self) {
let _ = self.name.handle(InputRequest::GoToPrevChar);
}
}
impl PartialComponent for RenameAccount {
fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab {
CurrentTab::RenameAccount => self.is_active = true,
_ => {
self.is_active = false;
self.old_name = String::new();
self.name = Input::new(String::new());
}
};
}
}
impl Component for RenameAccount {
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
self.action_tx = Some(tx);
Ok(())
}
fn register_config_handler(&mut self, config: Config) -> Result<()> {
if let Some(style) = config.styles.get(&crate::app::Mode::Explorer) {
self.palette.with_normal_style(style.get("normal_style").copied());
self.palette.with_normal_border_style(style.get("normal_border_style").copied());
self.palette.with_normal_title_style(style.get("normal_title_style").copied());
}
Ok(())
}
fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::RenameAccount(old_name) => self.old_name = old_name,
_ => {}
};
Ok(None)
}
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if self.is_active && key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Enter => self.submit_message(),
KeyCode::Char(to_insert) => self.enter_char(to_insert),
KeyCode::Backspace => self.delete_char(),
KeyCode::Left => self.move_cursor_left(),
KeyCode::Right => self.move_cursor_right(),
KeyCode::Esc => self.is_active = false,
_ => {},
};
}
Ok(None)
}
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
if self.is_active {
let input = Paragraph::new(self.name.value())
.block(Block::bordered()
.title_alignment(Alignment::Right)
.title(format!("New name for '{}'", self.old_name)));
let v = Layout::vertical([Constraint::Max(3)]).flex(Flex::Center);
let h = Layout::horizontal([Constraint::Max(50)]).flex(Flex::Center);
let [area] = v.areas(area);
let [area] = h.areas(area);
frame.render_widget(Clear, area);
frame.render_widget(input, area);
frame.set_cursor_position(Position::new(
area.x + self.name.cursor() as u16 + 1,
area.y + 1
));
}
Ok(())
}
}

View File

@ -1,141 +0,0 @@
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind};
use color_eyre::Result;
use ratatui::{
layout::{Position, Alignment, Constraint, Flex, Layout, Rect},
widgets::{Block, Clear, Paragraph},
Frame
};
use tokio::sync::mpsc::UnboundedSender;
use super::{Component, PartialComponent, CurrentTab};
use crate::{
widgets::{Input, InputRequest},
action::Action,
config::Config,
palette::StylePalette,
};
#[derive(Debug)]
pub struct RenameAddressBookRecord {
is_active: bool,
action_tx: Option<UnboundedSender<Action>>,
old_name: String,
name: Input,
palette: StylePalette
}
impl Default for RenameAddressBookRecord {
fn default() -> Self {
Self::new()
}
}
impl RenameAddressBookRecord {
pub fn new() -> Self {
Self {
is_active: false,
old_name: String::new(),
action_tx: None,
name: Input::new(String::new()),
palette: StylePalette::default(),
}
}
}
impl RenameAddressBookRecord {
fn submit_message(&mut self) {
if let Some(action_tx) = &self.action_tx {
let _ = action_tx.send(Action::UpdateAddressBookRecord(
self.name.value().to_string()));
}
}
fn enter_char(&mut self, new_char: char) {
let _ = self.name.handle(InputRequest::InsertChar(new_char));
}
fn delete_char(&mut self) {
let _ = self.name.handle(InputRequest::DeletePrevChar);
}
fn move_cursor_right(&mut self) {
let _ = self.name.handle(InputRequest::GoToNextChar);
}
fn move_cursor_left(&mut self) {
let _ = self.name.handle(InputRequest::GoToPrevChar);
}
}
impl PartialComponent for RenameAddressBookRecord {
fn set_active(&mut self, current_tab: CurrentTab) {
match current_tab {
CurrentTab::RenameAddressBookRecord => self.is_active = true,
_ => {
self.is_active = false;
self.old_name = String::new();
self.name = Input::new(String::new());
}
};
}
}
impl Component for RenameAddressBookRecord {
fn register_action_handler(&mut self, tx: UnboundedSender<Action>) -> Result<()> {
self.action_tx = Some(tx);
Ok(())
}
fn register_config_handler(&mut self, config: Config) -> Result<()> {
if let Some(style) = config.styles.get(&crate::app::Mode::Wallet) {
self.palette.with_normal_style(style.get("normal_style").copied());
self.palette.with_normal_border_style(style.get("normal_border_style").copied());
self.palette.with_normal_title_style(style.get("normal_title_style").copied());
}
Ok(())
}
fn update(&mut self, action: Action) -> Result<Option<Action>> {
match action {
Action::RenameAddressBookRecord(old_name) => self.old_name = old_name,
_ => {}
};
Ok(None)
}
fn handle_key_event(&mut self, key: KeyEvent) -> Result<Option<Action>> {
if self.is_active && key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Enter => self.submit_message(),
KeyCode::Char(to_insert) => self.enter_char(to_insert),
KeyCode::Backspace => self.delete_char(),
KeyCode::Left => self.move_cursor_left(),
KeyCode::Right => self.move_cursor_right(),
KeyCode::Esc => self.is_active = false,
_ => {},
};
}
Ok(None)
}
fn draw(&mut self, frame: &mut Frame, area: Rect) -> Result<()> {
if self.is_active {
let input = Paragraph::new(self.name.value())
.block(Block::bordered()
.title_alignment(Alignment::Right)
.title(format!("New name for '{}'", self.old_name)));
let v = Layout::vertical([Constraint::Max(3)]).flex(Flex::Center);
let h = Layout::horizontal([Constraint::Max(50)]).flex(Flex::Center);
let [area] = v.areas(area);
let [area] = h.areas(area);
frame.render_widget(Clear, area);
frame.render_widget(input, area);
frame.set_cursor_position(Position::new(
area.x + self.name.cursor() as u16 + 1,
area.y + 1
));
}
Ok(())
}
}

View File

@ -1,10 +0,0 @@
use serde::{Deserialize, Serialize};
use strum::Display;
#[derive(Default, Debug, Clone, PartialEq, Eq, Display, Serialize, Deserialize)]
pub enum ActionLevel {
#[default]
Info,
Warn,
Error,
}

View File

@ -1,7 +1,5 @@
mod era; mod era;
mod extrinsics; mod extrinsics;
mod log;
pub use extrinsics::CasperExtrinsicDetails; pub use extrinsics::CasperExtrinsicDetails;
pub use era::EraInfo; pub use era::EraInfo;
pub use log::ActionLevel;