Skip to content

Commit

Permalink
feat: adding better comments througout the app
Browse files Browse the repository at this point in the history
  • Loading branch information
wllfaria committed May 23, 2024
1 parent de075c4 commit ba32aeb
Show file tree
Hide file tree
Showing 20 changed files with 219 additions and 159 deletions.
2 changes: 1 addition & 1 deletion config/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn get_data_dir() -> PathBuf {
}

#[tracing::instrument(err)]
pub fn get_schemas_dir() -> anyhow::Result<PathBuf> {
pub fn get_collections_dir() -> anyhow::Result<PathBuf> {
let data_dir = get_data_dir();
let schemas_dir = data_dir.join(SCHEMAS_DIR);

Expand Down
2 changes: 1 addition & 1 deletion config/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mod data;
mod default_config;

pub use config::{load_config, Action, Config, KeyAction};
pub use data::{get_schemas_dir, setup_data_dir};
pub use data::{get_collections_dir, setup_data_dir};
use serde::{Deserialize, Serialize};

#[derive(PartialEq, Deserialize, Serialize, Debug, Clone)]
Expand Down
5 changes: 3 additions & 2 deletions reqtui/src/schema/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::{

#[tracing::instrument(err)]
pub fn get_schemas_from_config() -> anyhow::Result<Vec<Schema>> {
let schemas_dir = config::get_schemas_dir()?;
let schemas_dir = config::get_collections_dir()?;
get_schemas(schemas_dir)
}

Expand Down Expand Up @@ -48,7 +48,8 @@ pub fn create_from_form(name: String, description: String) -> anyhow::Result<Sch
name
};

let schemas_dir = config::get_schemas_dir().map_err(|e| SchemaError::IOError(e.to_string()))?;
let schemas_dir =
config::get_collections_dir().map_err(|e| SchemaError::IOError(e.to_string()))?;
let name_as_file_name = name.to_lowercase().replace(' ', "_");
let schema_name = schemas_dir.join(name_as_file_name);

Expand Down
2 changes: 1 addition & 1 deletion tui/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,5 +36,5 @@ bench = false
path = "src/main.rs"

[[bench]]
name = "api_explorer"
name = "collection_viewer_bench"
harness = false
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use reqtui::{
};
use tree_sitter::Tree;
use tui::{
components::{api_explorer::ApiExplorer, Component, Eventful},
utils::build_styled_content,
components::{api_explorer::CollectionViewer, Eventful, Page},
utils::build_syntax_highlighted_lines,
};

fn main() {
Expand Down Expand Up @@ -46,7 +46,7 @@ fn create_sample_schema() -> Schema {
}
}

fn feed_keys(widget: &mut ApiExplorer, key_codes: Vec<KeyCode>) {
fn feed_keys(widget: &mut CollectionViewer, key_codes: Vec<KeyCode>) {
key_codes.into_iter().for_each(|code| {
widget
.handle_key_event(KeyEvent {
Expand All @@ -65,7 +65,7 @@ fn handling_key_events() {
let schema = create_sample_schema();
let size = Rect::new(0, 0, 80, 24);
let config = config::load_config();
let mut api_explorer = ApiExplorer::new(size, schema, &colors, &config);
let mut api_explorer = CollectionViewer::new(size, schema, &colors, &config);
let mut terminal = Terminal::new(TestBackend::new(size.width, size.height)).unwrap();
let mut frame = terminal.get_frame();

Expand Down Expand Up @@ -93,7 +93,7 @@ fn creating_with_highlight() {
let schema = create_sample_schema();
let size = Rect::new(0, 0, 80, 24);
let config = config::load_config();
let mut api_explorer = ApiExplorer::new(size, schema, &colors, &config);
let mut api_explorer = CollectionViewer::new(size, schema, &colors, &config);
let mut terminal = Terminal::new(TestBackend::new(size.width, size.height)).unwrap();
let _frame = terminal.get_frame();

Expand Down Expand Up @@ -141,5 +141,5 @@ lazy_static! {
#[divan::bench]
fn benchmarking_building_content() {
let colors = colors::Colors::default();
build_styled_content(&BODY, TREE.as_ref(), &colors);
build_syntax_highlighted_lines(&BODY, TREE.as_ref(), &colors);
}
32 changes: 19 additions & 13 deletions tui/src/app.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{
components::{Component, Eventful},
components::{Eventful, Page},
event_pool::{Event, EventPool},
screen_manager::ScreenManager,
};
Expand Down Expand Up @@ -30,6 +30,8 @@ impl<'app> App<'app> {
})
}

/// this is the main method which starts the event loop task, listen for events and commands
/// to pass them down the chain, and render the terminal screen
pub async fn run(&mut self) -> anyhow::Result<()> {
let (command_tx, mut command_rx) = mpsc::unbounded_channel();
self.event_pool.start();
Expand All @@ -54,22 +56,22 @@ impl<'app> App<'app> {
}
})?;
}
_ => {}
event => {
if let Some(command) =
self.screen_manager.handle_event(Some(event.clone()))?
{
command_tx
.send(command)
.expect("failed to send command through channel")
}
}
};

if let Some(command) = self.screen_manager.handle_event(Some(event.clone()))? {
command_tx
.send(command)
.expect("failed to send command through channel")
}
}

while let Ok(command) = command_rx.try_recv() {
match command {
Command::Quit => self.should_quit = true,
Command::SelectSchema(_) => self.screen_manager.handle_command(command),
Command::CreateSchema(_) => self.screen_manager.handle_command(command),
Command::Error(_) => self.screen_manager.handle_command(command),
_ => self.screen_manager.handle_command(command),
}
}

Expand All @@ -83,14 +85,18 @@ impl<'app> App<'app> {
}
}

/// before initializing the app, we must setup the terminal to enable all the features
/// we need, such as raw mode and entering the alternate screen
fn startup() -> anyhow::Result<()> {
crossterm::terminal::enable_raw_mode()?;
crossterm::execute!(std::io::stdout(), crossterm::terminal::EnterAlternateScreen,)?;
crossterm::execute!(std::io::stdout(), crossterm::terminal::EnterAlternateScreen)?;
Ok(())
}

/// before shutting down we must reverse the changes we made to the users terminal, allowing
/// them have a usable terminal
fn shutdown() -> anyhow::Result<()> {
crossterm::terminal::disable_raw_mode()?;
crossterm::execute!(std::io::stdout(), crossterm::terminal::LeaveAlternateScreen,)?;
crossterm::execute!(std::io::stdout(), crossterm::terminal::LeaveAlternateScreen)?;
Ok(())
}
45 changes: 29 additions & 16 deletions tui/src/components.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,35 @@ use ratatui::{layout::Rect, Frame};
use reqtui::command::Command;
use tokio::sync::mpsc::UnboundedSender;

/// A `Page` is anything that is a top level page and can be drawn to the screen
pub trait Page {
fn draw(&mut self, frame: &mut Frame, size: Rect) -> anyhow::Result<()>;

/// pages need to adapt to change of sizes on the application, this function is called
/// by the top level event loop whenever a resize event is produced
#[allow(unused_variables)]
fn resize(&mut self, new_size: Rect);

/// register a page to be a command handler, which means this page will now receive
/// commands from the channel to handle whatever the commands it is interested into
#[allow(unused_variables)]
fn register_command_handler(&mut self, sender: UnboundedSender<Command>) -> anyhow::Result<()> {
Ok(())
}

/// tick is a smaller interval than the one used by the render cycle, it is mainly used
/// for actions that rely on time, such as auto-syncing the edited request on the
/// CollectionViewer
fn handle_tick(&mut self) -> anyhow::Result<()> {
Ok(())
}
}

/// An `Eventful` component is a component that can handle key events, and mouse events
/// when support for them gets added.
pub trait Eventful {
/// the top level event loop doesnt differentiate between kinds of events, so this is what
/// delegate each kind of events to the responsible function
fn handle_event(&mut self, event: Option<Event>) -> anyhow::Result<Option<Command>> {
let action = match event {
Some(Event::Key(key_event)) => self.handle_key_event(key_event)?,
Expand All @@ -22,24 +50,9 @@ pub trait Eventful {
Ok(action)
}

/// when we get a key_event, this will be called for the eventful component to handle it
#[allow(unused_variables)]
fn handle_key_event(&mut self, key_event: KeyEvent) -> anyhow::Result<Option<Command>> {
Ok(None)
}
}

pub trait Component {
fn draw(&mut self, frame: &mut Frame, size: Rect) -> anyhow::Result<()>;

#[allow(unused_variables)]
fn resize(&mut self, new_size: Rect) {}

#[allow(unused_variables)]
fn register_command_handler(&mut self, sender: UnboundedSender<Command>) -> anyhow::Result<()> {
Ok(())
}

fn handle_tick(&mut self) -> anyhow::Result<()> {
Ok(())
}
}
12 changes: 6 additions & 6 deletions tui/src/components/api_explorer/api_explorer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::components::{
},
input::Input,
overlay::draw_overlay,
Component, Eventful,
Eventful, Page,
};
use anyhow::Context;
use config::EditorMode;
Expand Down Expand Up @@ -121,7 +121,7 @@ pub enum CreateReqKind {
}

#[derive(Debug)]
pub struct ApiExplorer<'ae> {
pub struct CollectionViewer<'ae> {
schema: Schema,
colors: &'ae colors::Colors,
config: &'ae config::Config,
Expand Down Expand Up @@ -153,7 +153,7 @@ pub struct ApiExplorer<'ae> {
responses_map: HashMap<Request, Rc<RefCell<ReqtuiResponse>>>,
}

impl<'ae> ApiExplorer<'ae> {
impl<'ae> CollectionViewer<'ae> {
pub fn new(
size: Rect,
schema: Schema,
Expand All @@ -179,7 +179,7 @@ impl<'ae> ApiExplorer<'ae> {

let (request_tx, response_rx) = unbounded_channel::<ReqtuiNetRequest>();

ApiExplorer {
CollectionViewer {
schema,
focused_pane: PaneFocus::ReqUri,
selected_pane: None,
Expand Down Expand Up @@ -825,7 +825,7 @@ impl<'ae> ApiExplorer<'ae> {
}
}

impl Component for ApiExplorer<'_> {
impl Page for CollectionViewer<'_> {
#[tracing::instrument(skip_all, target = "api_explorer")]
fn draw(&mut self, frame: &mut Frame, size: Rect) -> anyhow::Result<()> {
self.draw_background(size, frame);
Expand Down Expand Up @@ -897,7 +897,7 @@ impl Component for ApiExplorer<'_> {
}
}

impl Eventful for ApiExplorer<'_> {
impl Eventful for CollectionViewer<'_> {
fn handle_key_event(&mut self, key_event: KeyEvent) -> anyhow::Result<Option<Command>> {
if self.curr_overlay.ne(&Overlays::None) {
match self.curr_overlay {
Expand Down
2 changes: 1 addition & 1 deletion tui/src/components/api_explorer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ mod req_uri;
mod res_viewer;
mod sidebar;

pub use api_explorer::ApiExplorer;
pub use api_explorer::CollectionViewer;
13 changes: 8 additions & 5 deletions tui/src/components/api_explorer/req_editor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{components::Eventful, utils::build_styled_content};
use crate::{components::Eventful, utils::build_syntax_highlighted_lines};
use config::{Action, EditorMode, KeyAction};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
Expand Down Expand Up @@ -122,7 +122,7 @@ impl<'re> ReqEditor<'re> {
};

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

Self {
colors,
Expand Down Expand Up @@ -670,8 +670,11 @@ impl Eventful for ReqEditor<'_> {
}

self.tree = HIGHLIGHTER.write().unwrap().parse(&self.body.to_string());
self.styled_display =
build_styled_content(&self.body.to_string(), self.tree.as_ref(), self.colors);
self.styled_display = build_syntax_highlighted_lines(
&self.body.to_string(),
self.tree.as_ref(),
self.colors,
);
return Ok(None);
}

Expand Down Expand Up @@ -706,7 +709,7 @@ impl Eventful for ReqEditor<'_> {

self.tree = HIGHLIGHTER.write().unwrap().parse(&self.body.to_string());
self.styled_display =
build_styled_content(&self.body.to_string(), self.tree.as_ref(), self.colors);
build_syntax_highlighted_lines(&self.body.to_string(), self.tree.as_ref(), self.colors);

Ok(None)
}
Expand Down
5 changes: 3 additions & 2 deletions tui/src/components/api_explorer/res_viewer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use reqtui::{net::request_manager::ReqtuiResponse, syntax::highlighter::HIGHLIGHTER};

use crate::utils::build_styled_content;
use crate::utils::build_syntax_highlighted_lines;
use ratatui::{
buffer::Buffer,
layout::{Constraint, Direction, Layout, Rect},
Expand Down Expand Up @@ -119,7 +119,8 @@ impl<'a> ResViewer<'a> {

if let Some(ref res) = response {
let pretty_body = res.borrow().pretty_body.to_string();
self.lines = build_styled_content(&pretty_body, self.tree.as_ref(), self.colors);
self.lines =
build_syntax_highlighted_lines(&pretty_body, self.tree.as_ref(), self.colors);
}

self.response = response;
Expand Down
Loading

0 comments on commit ba32aeb

Please sign in to comment.