Skip to content

Commit

Permalink
feat: deleting requests and headers
Browse files Browse the repository at this point in the history
  • Loading branch information
wllfaria committed Jun 15, 2024
1 parent 2bf01fd commit b914655
Show file tree
Hide file tree
Showing 11 changed files with 520 additions and 83 deletions.
49 changes: 45 additions & 4 deletions hac-client/src/pages/collection_viewer/collection_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub struct CollectionStore {
state: Option<Rc<RefCell<CollectionState>>>,
}

#[derive(Debug)]
pub enum CollectionStoreAction {
SetSelectedRequest(Option<Arc<RwLock<Request>>>),
SetHoveredRequest(Option<String>),
Expand Down Expand Up @@ -199,10 +200,18 @@ impl CollectionStore {
}

fn maybe_hover_prev(&mut self) {
if self.get_hovered_request().is_some() && self.get_requests().is_some() {
let id = self.get_hovered_request().unwrap();
if self.get_requests().is_some() {
let requests = self.get_requests().unwrap();

let Some(id) = self.get_hovered_request() else {
tracing::debug!("{:?}", self.get_hovered_request());
self.dispatch(CollectionStoreAction::SetHoveredRequest(
requests.read().unwrap().first().map(|req| req.get_id()),
));
tracing::debug!("{:?}", self.get_hovered_request());
return;
};

if let Some(next) = find_next_entry(
&requests.read().unwrap(),
VisitNode::Prev,
Expand All @@ -217,10 +226,18 @@ impl CollectionStore {
}

fn maybe_hover_next(&mut self) {
if self.get_hovered_request().is_some() && self.get_requests().is_some() {
let id = self.get_hovered_request().unwrap();
if self.get_requests().is_some() {
let requests = self.get_requests().unwrap();

let Some(id) = self.get_hovered_request() else {
tracing::debug!("{:?}", self.get_hovered_request());
self.dispatch(CollectionStoreAction::SetHoveredRequest(
requests.read().unwrap().first().map(|req| req.get_id()),
));
tracing::debug!("{:?}", self.get_hovered_request());
return;
};

if let Some(next) = find_next_entry(
&requests.read().unwrap(),
VisitNode::Next,
Expand All @@ -241,6 +258,28 @@ impl CollectionStore {
self.get_hovered_request().as_ref().unwrap(),
)
}

pub fn remove_item(&mut self, item_id: String) {
if let Some(request) = self.get_selected_request() {
if request.read().unwrap().id.eq(&item_id) {
self.dispatch(CollectionStoreAction::SetSelectedRequest(None));
}
}
let mut requests = self.get_requests();
let mut requests = requests.as_mut().unwrap().write().unwrap();
requests.retain(|req| req.get_id().ne(&item_id));
requests.iter_mut().for_each(|req| {
if let RequestKind::Nested(dir) = req {
dir.requests
.write()
.unwrap()
.retain(|child| child.get_id().ne(&item_id));
}
});
self.dispatch(CollectionStoreAction::SetHoveredRequest(
requests.first().map(|req| req.get_id()),
));
}
}

#[derive(PartialEq)]
Expand Down Expand Up @@ -276,6 +315,8 @@ fn traverse(
// We are looking for the next and just found the current one, so we set the flag to
// true in order to know when to return the next.
(VisitNode::Next, true, false) => *found = true,
// we are looking for the current node and we found it, so we set the flag to true
// and return immediatly
(VisitNode::Curr, true, _) => {
path.push(current.clone());
*found = true;
Expand Down
34 changes: 33 additions & 1 deletion hac-client/src/pages/collection_viewer/collection_viewer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub struct ExplorerLayout {
pub create_req_form: Rect,
}

#[derive(Debug, Clone)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum CollectionViewerOverlay {
None,
CreateRequest,
Expand All @@ -41,6 +41,7 @@ pub enum CollectionViewerOverlay {
HeadersHelp,
HeadersDelete,
HeadersForm(usize),
DeleteSidebarItem(String),
}

#[derive(Debug, Clone, Copy, PartialEq)]
Expand Down Expand Up @@ -79,6 +80,7 @@ pub struct CollectionViewer<'cv> {
sidebar: Sidebar<'cv>,

colors: &'cv hac_colors::Colors,
config: &'cv hac_config::Config,
layout: ExplorerLayout,
global_command_sender: Option<UnboundedSender<Command>>,
collection_sync_timer: std::time::Instant,
Expand Down Expand Up @@ -123,6 +125,7 @@ impl<'cv> CollectionViewer<'cv> {
request_uri,
colors,
layout,
config,
global_command_sender: None,
collection_sync_timer: std::time::Instant::now(),
responses_map: HashMap::default(),
Expand All @@ -133,6 +136,27 @@ impl<'cv> CollectionViewer<'cv> {
}
}

fn rebuild_everything(&mut self) {
self.sidebar = sidebar::Sidebar::new(self.colors, self.collection_store.clone());
self.request_editor = RequestEditor::new(
self.colors,
self.config,
self.collection_store.clone(),
self.layout.req_editor,
);
self.response_viewer = ResponseViewer::new(
self.colors,
self.collection_store.clone(),
None,
self.layout.response_preview,
);
self.request_uri = RequestUri::new(
self.colors,
self.collection_store.clone(),
self.layout.req_uri,
);
}

// collect all pending responses from the channel. Here, I don't see a way we
// may have more than one response on this channel at any point, but it shouldn't matter
// if we have, so we can drain all the responses and update accordingly
Expand Down Expand Up @@ -271,6 +295,9 @@ impl Renderable for CollectionViewer<'_> {
CollectionViewerOverlay::EditRequest => {
self.sidebar.draw_overlay(frame, overlay)?;
}
CollectionViewerOverlay::DeleteSidebarItem(_) => {
self.sidebar.draw_overlay(frame, overlay)?;
}
CollectionViewerOverlay::HeadersHelp => {
self.request_editor.draw_overlay(frame, overlay)?;
}
Expand Down Expand Up @@ -409,9 +436,14 @@ impl Eventful for CollectionViewer<'_> {
.collection_store
.borrow_mut()
.push_overlay(CollectionViewerOverlay::CreateDirectory),
Some(SidebarEvent::DeleteItem(item_id)) => self
.collection_store
.borrow_mut()
.push_overlay(CollectionViewerOverlay::DeleteSidebarItem(item_id)),
Some(SidebarEvent::RemoveSelection) => self.update_selection(None),
Some(SidebarEvent::SyncCollection) => self.sync_collection_changes(),
Some(SidebarEvent::Quit) => return Ok(Some(Command::Quit)),
Some(SidebarEvent::RebuildView) => self.rebuild_everything(),
// when theres no event we do nothing
None => {}
},
Expand Down
1 change: 0 additions & 1 deletion hac-client/src/pages/collection_viewer/request_editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ pub struct RequestEditor<'re> {
body_editor: BodyEditor<'re>,
headers_editor: HeadersEditor<'re>,
auth_editor: AuthEditor<'re>,

layout: ReqEditorLayout,
curr_tab: ReqEditorTabs,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub struct BodyEditor<'be> {
/// Only KeyAction::Complex are stored here as any other kind of key action can be acted upon
/// instantly
keymap_buffer: Option<KeyAction>,
collection_store: Rc<RefCell<CollectionStore>>,
}

impl<'be> BodyEditor<'be> {
Expand All @@ -52,25 +53,14 @@ impl<'be> BodyEditor<'be> {
collection_store: Rc<RefCell<CollectionStore>>,
size: Rect,
) -> Self {
let (body, tree) = if let Some(request) = collection_store.borrow().get_selected_request() {
if let Some(body) = request.read().unwrap().body.as_ref() {
let mut highlighter = HIGHLIGHTER.write().unwrap();
let tree = highlighter.parse(body);

(TextObject::from(body).with_write(), tree)
} else {
Default::default()
}
} else {
Default::default()
};

let (body, tree) = make_body(&collection_store);
let content = body.to_string();
let styled_display = build_syntax_highlighted_lines(&content, tree.as_ref(), colors);

Self {
body,
tree,
collection_store,
styled_display,
cursor: Cursor::default(),
editor_mode: EditorMode::Normal,
Expand Down Expand Up @@ -662,3 +652,20 @@ fn get_visible_spans(line: &Line<'static>, scroll: usize) -> Line<'static> {

Line::from(new_spans)
}

fn make_body(collection_store: &Rc<RefCell<CollectionStore>>) -> (TextObject<Write>, Option<Tree>) {
let (body, tree) = if let Some(request) = collection_store.borrow().get_selected_request() {
if let Some(body) = request.read().unwrap().body.as_ref() {
let mut highlighter = HIGHLIGHTER.write().unwrap();
let tree = highlighter.parse(body);

(TextObject::from(body).with_write(), tree)
} else {
Default::default()
}
} else {
Default::default()
};

(body, tree)
}
51 changes: 50 additions & 1 deletion hac-client/src/pages/collection_viewer/sidebar.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
mod create_directory_form;
mod create_request_form;
mod delete_item_prompt;
mod edit_request_form;
mod request_form;
mod select_request_parent;

use hac_core::collection::types::{Request, RequestKind, RequestMethod};

use super::sidebar::create_directory_form::{CreateDirectoryForm, CreateDirectoryFormEvent};
use super::sidebar::delete_item_prompt::{DeleteItemPrompt, DeleteItemPromptEvent};
use super::sidebar::request_form::RequestForm;
use super::sidebar::request_form::RequestFormCreate;
use super::sidebar::request_form::RequestFormEdit;
Expand All @@ -28,7 +30,7 @@ use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::Frame;

/// set of events Sidebar can emit to the caller when handling events.
#[derive(Debug)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum SidebarEvent {
/// user pressed `CreateRequest (n)` hotkey, which should notify the caller to open
/// the create_request_form and properly handle the creation of a new request
Expand All @@ -42,9 +44,14 @@ pub enum SidebarEvent {
/// user pressed `Esc` so we notify the caller to remove the selection from
/// this pane, essentially bubbling the key handling scope to the caller
RemoveSelection,
/// event to force a full rebuild of the view, when a request is deleted
RebuildView,
/// this event is used when a request or directory is created, this notify the parent
/// to sync changes with the file system.
SyncCollection,
/// user pressed `DeleteItem (D)` hotkey, which should notify the caller to open the
/// delete_item_prompt to ask the user for confirmation
DeleteItem(String),
/// user pressed a hotkey to quit the application, so we bubble up so the caller
/// can do a few things before bubbling the quit request further up
Quit,
Expand Down Expand Up @@ -83,6 +90,7 @@ pub struct Sidebar<'sbar> {
collection_store: Rc<RefCell<CollectionStore>>,
request_form: FormVariant<'sbar>,
directory_form: CreateDirectoryForm<'sbar>,
delete_item_prompt: DeleteItemPrompt<'sbar>,
}

impl<'sbar> Sidebar<'sbar> {
Expand All @@ -97,6 +105,7 @@ impl<'sbar> Sidebar<'sbar> {
collection_store.clone(),
)),
directory_form: CreateDirectoryForm::new(colors, collection_store.clone()),
delete_item_prompt: DeleteItemPrompt::new(colors, collection_store.clone()),
lines: vec![],
collection_store,
};
Expand Down Expand Up @@ -136,6 +145,9 @@ impl<'sbar> Sidebar<'sbar> {
CollectionViewerOverlay::CreateDirectory => {
self.directory_form.draw(frame, frame.size())?;
}
CollectionViewerOverlay::DeleteSidebarItem(_) => {
self.delete_item_prompt.draw(frame, frame.size())?;
}
_ => {}
};

Expand Down Expand Up @@ -201,6 +213,8 @@ impl<'a> Eventful for Sidebar<'a> {

let overlay = self.collection_store.borrow_mut().peek_overlay();

tracing::debug!("{:?}", key_event.code);

match overlay {
CollectionViewerOverlay::CreateRequest => {
match self.request_form.inner().handle_key_event(key_event)? {
Expand Down Expand Up @@ -268,6 +282,34 @@ impl<'a> Eventful for Sidebar<'a> {
None => return Ok(None),
}
}
CollectionViewerOverlay::DeleteSidebarItem(item_id) => {
match self.delete_item_prompt.handle_key_event(key_event)? {
Some(DeleteItemPromptEvent::Confirm) => {
let mut store = self.collection_store.borrow_mut();
let changed_selection = store
.get_selected_request()
.is_some_and(|req| req.read().unwrap().id.eq(&item_id));
store.remove_item(item_id);
store.pop_overlay();
drop(store);
self.rebuild_tree_view();

if changed_selection {
return Ok(Some(SidebarEvent::RebuildView));
} else {
return Ok(None);
}
}
Some(DeleteItemPromptEvent::Cancel) => {
let mut store = self.collection_store.borrow_mut();
store.pop_overlay();
drop(store);
self.rebuild_tree_view();
return Ok(None);
}
None => return Ok(None),
}
}
_ => {}
};

Expand All @@ -290,6 +332,7 @@ impl<'a> Eventful for Sidebar<'a> {
}
RequestKind::Single(req) => {
store.dispatch(CollectionStoreAction::SetSelectedRequest(Some(req)));
return Ok(Some(SidebarEvent::RebuildView));
}
}
}
Expand All @@ -306,13 +349,19 @@ impl<'a> Eventful for Sidebar<'a> {
let RequestKind::Single(request) = store.find_hovered_request() else {
return Ok(None);
};
drop(store);
self.request_form = FormVariant::Edit(RequestForm::<RequestFormEdit>::new(
self.colors,
self.collection_store.clone(),
request.clone(),
));
return Ok(Some(SidebarEvent::EditRequest));
}
KeyCode::Char('D') => {
if let Some(item_id) = store.get_hovered_request() {
return Ok(Some(SidebarEvent::DeleteItem(item_id)));
}
}
KeyCode::Char('d') => return Ok(Some(SidebarEvent::CreateDirectory)),
KeyCode::Esc => return Ok(Some(SidebarEvent::RemoveSelection)),
_ => {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl Renderable for CreateDirectoryForm<'_> {

let logo = logo
.iter()
.map(|line| Line::from(line.to_string().fg(self.colors.normal.red)))
.map(|line| Line::from(line.to_string().fg(self.colors.normal.red)).centered())
.collect::<Vec<_>>();

let mut input = Input::new(self.colors, "Name".into());
Expand Down
Loading

0 comments on commit b914655

Please sign in to comment.