Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::{
client::Client,
color::ColorTheme,
config::Config,
data::{Item, Table, TableDescription, TableInsight},
data::{to_key_string, Item, Table, TableDescription, TableInsight},
error::{AppError, AppResult},
event::{AppEvent, Receiver, Sender, UserEvent, UserEventMapper},
handle_user_events,
Expand Down Expand Up @@ -147,6 +147,12 @@ impl App {
AppEvent::CopyToClipboard(name, content) => {
self.copy_to_clipboard(name, content);
}
AppEvent::DeleteItem(desc, item) => {
self.delete_item(desc, item);
}
AppEvent::CompleteDeleteItem(desc, key_string, result) => {
self.complete_delete_item(desc, key_string, result);
}
AppEvent::ClearStatus => {
self.clear_status();
}
Expand Down Expand Up @@ -349,6 +355,38 @@ impl App {
}
}

fn delete_item(&mut self, desc: TableDescription, item: Item) {
self.loading = true;
let client = self.client.clone();
let tx = self.tx.clone();
let schema = desc.key_schema_type.clone();
let table_name = desc.table_name.clone();
let key_string = to_key_string(&item, &schema);
spawn(async move {
let result = client.delete_item(&table_name, &schema, &item).await;
tx.send(AppEvent::CompleteDeleteItem(desc, key_string, result));
});
}

fn complete_delete_item(
&mut self,
desc: TableDescription,
key_string: String,
result: AppResult<()>,
) {
match result {
Ok(()) => {
let msg = format!("Deleted item {key_string}");
self.tx.send(AppEvent::NotifySuccess(msg));
self.load_table_items(desc);
}
Err(e) => {
self.loading = false;
self.tx.send(AppEvent::NotifyError(e));
}
}
}

fn clear_status(&mut self) {
self.status = Status::None;
}
Expand Down
77 changes: 76 additions & 1 deletion src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use aws_sdk_dynamodb::types::{
ScalarAttributeType as AwsScalarAttributeType, TableDescription as AwsTableDescription,
TableStatus as AwsTableStatus,
};
use aws_smithy_types::DateTime as AwsDateTime;
use aws_smithy_types::{Blob, DateTime as AwsDateTime};
use chrono::{DateTime, Local, TimeZone as _};
use rust_decimal::Decimal;

Expand Down Expand Up @@ -127,6 +127,26 @@ impl Client {
sort_items(&mut items, schema);
Ok(items)
}

pub async fn delete_item(
&self,
table_name: &str,
schema: &KeySchemaType,
item: &Item,
) -> AppResult<()> {
let key = build_key_attributes(item, schema);
let result = self
.client
.delete_item()
.table_name(table_name)
.set_key(Some(key))
.send()
.await;

result
.map(|_| ())
.map_err(|e| AppError::new("failed to delete item", e))
}
}

impl From<String> for Table {
Expand Down Expand Up @@ -317,6 +337,61 @@ fn to_item(attributes: HashMap<String, AwsAttributeValue>) -> Item {
Item { attributes }
}

fn build_key_attributes(item: &Item, schema: &KeySchemaType) -> HashMap<String, AwsAttributeValue> {
match schema {
KeySchemaType::Hash(hash_key) => {
let mut key = HashMap::with_capacity(1);
let attr = item
.attributes
.get(hash_key)
.expect("missing hash key attribute");
key.insert(hash_key.clone(), attribute_to_aws(attr));
key
}
KeySchemaType::HashRange(hash_key, range_key) => {
let mut key = HashMap::with_capacity(2);
let hash_attr = item
.attributes
.get(hash_key)
.expect("missing hash key attribute");
let range_attr = item
.attributes
.get(range_key)
.expect("missing range key attribute");
key.insert(hash_key.clone(), attribute_to_aws(hash_attr));
key.insert(range_key.clone(), attribute_to_aws(range_attr));
key
}
}
}

fn attribute_to_aws(attr: &Attribute) -> AwsAttributeValue {
match attr {
Attribute::S(s) => AwsAttributeValue::S(s.clone()),
Attribute::N(n) => AwsAttributeValue::N(n.to_string()),
Attribute::B(b) => AwsAttributeValue::B(Blob::new(b.clone())),
Attribute::BOOL(b) => AwsAttributeValue::Bool(*b),
Attribute::NULL => AwsAttributeValue::Null(true),
Attribute::L(list) => {
let values = list.iter().map(attribute_to_aws).collect();
AwsAttributeValue::L(values)
}
Attribute::M(map) => {
let values = map
.iter()
.map(|(k, v)| (k.clone(), attribute_to_aws(v)))
.collect();
AwsAttributeValue::M(values)
}
Attribute::SS(set) => AwsAttributeValue::Ss(set.iter().cloned().collect()),
Attribute::NS(set) => AwsAttributeValue::Ns(set.iter().map(|n| n.to_string()).collect()),
Attribute::BS(set) => {
let values = set.iter().cloned().map(Blob::new).collect();
AwsAttributeValue::Bs(values)
}
}
}

impl From<AwsAttributeValue> for Attribute {
fn from(value: AwsAttributeValue) -> Self {
match value {
Expand Down
5 changes: 5 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub enum AppEvent {
OpenHelp(Vec<Spans>),
BackToBeforeView,
CopyToClipboard(String, String),
DeleteItem(TableDescription, Item),
CompleteDeleteItem(TableDescription, String, AppResult<()>),
ClearStatus,
UpdateStatusInput(String, Option<u16>),
NotifySuccess(String),
Expand Down Expand Up @@ -104,6 +106,7 @@ pub enum UserEvent {
Narrow,
Reload,
CopyToClipboard,
Delete,
Help,
}

Expand Down Expand Up @@ -146,6 +149,8 @@ impl UserEventMapper {
(KeyEvent::new(KeyCode::Char('-'), KeyModifiers::NONE), UserEvent::Narrow),
(KeyEvent::new(KeyCode::Char('R'), KeyModifiers::NONE), UserEvent::Reload),
(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE), UserEvent::CopyToClipboard),
(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::NONE), UserEvent::Delete),
(KeyEvent::new(KeyCode::Delete, KeyModifiers::NONE), UserEvent::Delete),
(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE), UserEvent::Help),
];
UserEventMapper { map }
Expand Down
97 changes: 93 additions & 4 deletions src/view/table.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use ratatui::{
crossterm::event::KeyEvent,
crossterm::event::{KeyCode, KeyEvent},
layout::{Margin, Rect},
style::Stylize,
symbols::border,
Expand All @@ -13,8 +13,8 @@ use crate::{
config::UiTableConfig,
constant::APP_NAME,
data::{
list_attribute_keys, Attribute, Item, KeySchemaType, RawAttributeJsonWrapper, RawJsonItem,
TableDescription, TableInsight,
list_attribute_keys, to_key_string, Attribute, Item, KeySchemaType,
RawAttributeJsonWrapper, RawJsonItem, TableDescription, TableInsight,
},
event::{AppEvent, Sender, UserEvent, UserEventMapper},
handle_user_events,
Expand Down Expand Up @@ -45,6 +45,11 @@ pub struct TableView {
table_state: TableState,
attr_expanded: bool,
attr_scroll_lines_state: ScrollLinesState,
pending_delete: Option<PendingDelete>,
}

struct PendingDelete {
row_index: usize,
}

impl TableView {
Expand Down Expand Up @@ -80,12 +85,18 @@ impl TableView {
table_state,
attr_expanded: false,
attr_scroll_lines_state,
pending_delete: None,
}
}
}

impl TableView {
pub fn handle_user_key_event(&mut self, user_events: Vec<UserEvent>, _key_event: KeyEvent) {
pub fn handle_user_key_event(&mut self, user_events: Vec<UserEvent>, key_event: KeyEvent) {
if self.pending_delete.is_some() && self.handle_delete_confirmation(&user_events, key_event)
{
return;
}

if self.attr_expanded {
handle_user_events! { user_events =>
UserEvent::Close | UserEvent::Expand => {
Expand Down Expand Up @@ -127,6 +138,9 @@ impl TableView {
UserEvent::CopyToClipboard => {
self.copy_to_clipboard();
}
UserEvent::Delete => {
self.start_delete_confirmation();
}
UserEvent::Help => {
self.open_help();
}
Expand Down Expand Up @@ -199,6 +213,9 @@ impl TableView {
UserEvent::CopyToClipboard => {
self.copy_to_clipboard();
}
UserEvent::Delete => {
self.start_delete_confirmation();
}
UserEvent::Help => {
self.open_help();
}
Expand Down Expand Up @@ -256,6 +273,7 @@ fn build_helps(mapper: &UserEventMapper, theme: ColorTheme) -> (Vec<Spans>, Vec<
BuildHelpsItem::new(UserEvent::Narrow, "Narrow selected column"),
BuildHelpsItem::new(UserEvent::Reload, "Reload table data"),
BuildHelpsItem::new(UserEvent::CopyToClipboard, "Copy selected item"),
BuildHelpsItem::new(UserEvent::Delete, "Delete selected item"),
];
#[rustfmt::skip]
let attr_helps = vec![
Expand All @@ -273,6 +291,7 @@ fn build_helps(mapper: &UserEventMapper, theme: ColorTheme) -> (Vec<Spans>, Vec<
BuildHelpsItem::new(UserEvent::ToggleNumber, "Toggle number"),
BuildHelpsItem::new(UserEvent::Reload, "Reload table data"),
BuildHelpsItem::new(UserEvent::CopyToClipboard, "Copy selected item"),
BuildHelpsItem::new(UserEvent::Delete, "Delete selected item"),
];
(
build_help_spans(table_helps, mapper, theme),
Expand All @@ -294,6 +313,7 @@ fn build_short_helps(mapper: &UserEventMapper) -> (Vec<SpansWithPriority>, Vec<S
BuildShortHelpsItem::single(UserEvent::CopyToClipboard, "Copy", 7),
BuildShortHelpsItem::group(vec![UserEvent::Widen, UserEvent::Narrow], "Widen/Narrow", 9),
BuildShortHelpsItem::single(UserEvent::Reload, "Reload", 8),
BuildShortHelpsItem::single(UserEvent::Delete, "Delete", 11),
BuildShortHelpsItem::single(UserEvent::Help, "Help", 0),
];
#[rustfmt::skip]
Expand All @@ -305,6 +325,7 @@ fn build_short_helps(mapper: &UserEventMapper) -> (Vec<SpansWithPriority>, Vec<S
BuildShortHelpsItem::group(vec![UserEvent::ToggleWrap, UserEvent::ToggleNumber], "Toggle wrap/number", 5),
BuildShortHelpsItem::single(UserEvent::CopyToClipboard, "Copy", 3),
BuildShortHelpsItem::single(UserEvent::Reload, "Reload", 4),
BuildShortHelpsItem::single(UserEvent::Delete, "Delete", 7),
BuildShortHelpsItem::single(UserEvent::Help, "Help", 0),
];
(
Expand Down Expand Up @@ -442,6 +463,74 @@ impl TableView {
self.tx.send(AppEvent::OpenHelp(self.table_helps.clone()))
}
}

fn start_delete_confirmation(&mut self) {
if self.pending_delete.is_some() {
return;
}
if let Some(item) = self.items.get(self.table_state.selected_row) {
let schema = &self.table_description.key_schema_type;
let key_string = to_key_string(item, schema);
let row_index = self.table_state.selected_row;
self.pending_delete = Some(PendingDelete { row_index });
let message = format!("Delete item {key_string}? (y/n)");
self.tx.send(AppEvent::UpdateStatusInput(message, None));
}
}

fn confirm_delete(&mut self) {
if let Some(pending) = self.pending_delete.take() {
self.tx.send(AppEvent::ClearStatus);
self.execute_delete(pending.row_index);
}
}

fn cancel_delete(&mut self) {
if self.pending_delete.take().is_some() {
self.tx.send(AppEvent::ClearStatus);
}
}

fn execute_delete(&mut self, row_index: usize) {
if let Some(item) = self.items.get(row_index) {
let desc = self.table_description.clone();
let item = item.clone();
self.attr_expanded = false;
self.tx.send(AppEvent::DeleteItem(desc, item));
}
}

fn handle_delete_confirmation(
&mut self,
user_events: &[UserEvent],
key_event: KeyEvent,
) -> bool {
if self.pending_delete.is_none() {
return false;
}

// if user_events.iter().any(|e| *e == UserEvent::Confirm) {
// self.confirm_delete();
// return true;
// }

if user_events.iter().any(|e| *e == UserEvent::Close) {
self.cancel_delete();
return true;
}

match key_event.code {
KeyCode::Char('y') | KeyCode::Char('Y') => {
self.confirm_delete();
true
}
KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
self.cancel_delete();
true
}
_ => true,
}
}
}

fn new_table_state(
Expand Down