Skip to content

Commit

Permalink
code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
pythops committed Oct 29, 2023
1 parent 04f4f9b commit ec234aa
Show file tree
Hide file tree
Showing 4 changed files with 194 additions and 170 deletions.
77 changes: 50 additions & 27 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ use std::collections::HashMap;
use std::sync::atomic::AtomicBool;

use crate::config::Config;
use crate::formatter::Formatter;
use crate::notification::Notification;
use crate::spinner::Spinner;
use crossterm::event::KeyCode;
use tui::widgets::ScrollbarState;
use tui::text::{Line, Text};

use std::sync::Arc;

Expand All @@ -25,54 +24,76 @@ pub enum FocusedBlock {
Chat,
History,
Preview,
Help,
}

#[derive(Debug, Default, Clone)]
pub struct History<'a> {
pub show: bool,
pub index: usize,
pub chat: Vec<Vec<String>>,
pub formatted_chat: Vec<Text<'a>>,
}

#[derive(Debug, Default)]
pub struct Chat<'a> {
pub messages: Vec<String>,
pub formatted_chat: Text<'a>,
}

#[derive(Debug)]
pub struct Prompt {
pub message: String,
}

impl Default for Prompt {
fn default() -> Self {
Self {
message: String::from(">_ "),
}
}
}

#[derive(Debug, Default)]
pub struct Answer<'a> {
pub answer: String,
pub formatted_answer: Text<'a>,
}

pub struct App<'a> {
pub prompt: String,
pub mode: Mode,
pub running: bool,
pub chat: Vec<String>,
pub scroll: usize,
pub prompt: Prompt,
pub mode: Mode,
pub chat: Chat<'a>,
pub previous_key: KeyCode,
pub focused_block: FocusedBlock,
pub show_help_popup: bool,
pub llm_messages: Vec<HashMap<String, String>>,
pub answer: String,
pub history: Vec<Vec<String>>,
pub show_history_popup: bool,
pub history_thread_index: usize,
pub answer: Answer<'a>,
pub history: History<'a>,
pub config: Arc<Config>,
pub notifications: Vec<Notification>,
pub spinner: Spinner,
pub terminate_response_signal: Arc<AtomicBool>,
pub chat_scroll_state: ScrollbarState,
pub chat_scroll: usize,
pub formatter: Formatter<'a>,
}

impl<'a> App<'a> {
pub fn new(config: Arc<Config>, formatter: Formatter<'a>) -> Self {
pub fn new(config: Arc<Config>) -> Self {
Self {
running: true,
prompt: String::from(">_ "),
mode: Mode::Normal,
chat: Vec::new(),
scroll: 0,
prompt: Prompt::default(),
mode: Mode::Normal,
chat: Chat::default(),
previous_key: KeyCode::Null,
focused_block: FocusedBlock::Prompt,
show_help_popup: false,
llm_messages: Vec::new(),
answer: String::new(),
history: Vec::new(),
show_history_popup: false,
history_thread_index: 0,
answer: Answer::default(),
history: History::default(),
config,
notifications: Vec::new(),
spinner: Spinner::default(),
terminate_response_signal: Arc::new(AtomicBool::new(false)),
chat_scroll_state: ScrollbarState::default(),
chat_scroll: 0,
formatter,
}
}

Expand All @@ -81,9 +102,11 @@ impl<'a> App<'a> {
self.notifications.iter_mut().for_each(|n| n.ttl -= 1);

if self.spinner.active {
self.chat.pop();
self.chat.formatted_chat.lines.pop();
self.chat
.push(format!("🤖: Waiting {}", self.spinner.draw()));
.formatted_chat
.lines
.push(Line::raw(format!("🤖: Waiting {}", self.spinner.draw())));
self.spinner.update();
}
}
Expand Down
113 changes: 63 additions & 50 deletions src/handler.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::app::{Chat, Prompt};
use crate::llm::LLMAnswer;

use crate::{
app::{App, AppResult, FocusedBlock, Mode},
event::Event,
Expand All @@ -10,6 +12,8 @@ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::sync::mpsc::Sender;
use std::{collections::HashMap, thread};

use tui::text::Line;

use crate::notification::{Notification, NotificationLevel};
use std::sync::Arc;

Expand Down Expand Up @@ -40,12 +44,19 @@ pub fn handle_key_events(

// Submit the prompt
KeyCode::Enter => {
let user_input: String = app.prompt.drain(3..).collect();
let user_input: String = app.prompt.message.drain(3..).collect();
let user_input = user_input.trim();

if user_input.is_empty() {
return Ok(());
}
app.chat.push(format!(" : {}\n", user_input));

app.chat.messages.push(format!(" : {}\n", user_input));

app.chat
.formatted_chat
.lines
.push(Line::raw(format!(" : {}\n", user_input)));

let conv = HashMap::from([
("role".into(), "user".into()),
Expand All @@ -56,7 +67,11 @@ pub fn handle_key_events(
let llm_messages = app.llm_messages.clone();

app.spinner.active = true;
app.chat.push("🤖: ".to_string());

app.chat
.formatted_chat
.lines
.push(Line::raw("🤖: ".to_string()));

let terminate_response_signal = app.terminate_response_signal.clone();

Expand All @@ -78,55 +93,54 @@ pub fn handle_key_events(
// scroll down
KeyCode::Char('j') | KeyCode::Down => match app.focused_block {
FocusedBlock::History => {
if app.history_thread_index < app.history.len() - 1 {
app.history_thread_index += 1;
if app.history.index < app.history.chat.len() - 1 {
app.history.index += 1;
}
}
_ => {
app.scroll = app.scroll.saturating_add(1);
app.chat_scroll_state = app.chat_scroll_state.position(app.scroll);
}
},

// scroll up
KeyCode::Char('k') | KeyCode::Up => match app.focused_block {
FocusedBlock::History => {
if app.history_thread_index > 0 {
app.history_thread_index -= 1;
if app.history.index > 0 {
app.history.index -= 1;
}
}
_ => {
app.scroll = app.scroll.saturating_sub(1);

app.chat_scroll_state = app.chat_scroll_state.position(app.scroll);
}
},

// Clear the prompt
KeyCode::Char('d') => {
if app.previous_key == KeyCode::Char('d') {
app.prompt = String::from(">_ ");
app.prompt = Prompt::default();
}
}

// New chat
KeyCode::Char(c) if c == app.config.key_bindings.new_chat => {
app.prompt = String::from(">_ ");
app.history.push(app.chat.clone());
app.chat = Vec::new();
app.prompt = Prompt::default();
app.history
.formatted_chat
.push(app.chat.formatted_chat.clone());
app.history.chat.push(app.chat.messages.clone());
app.chat = Chat::default();
app.llm_messages = Vec::new();
app.scroll = 0;
}

// Save chat
KeyCode::Char(c) if c == app.config.key_bindings.save_chat => match app.focused_block {
FocusedBlock::History | FocusedBlock::Preview => {
if !app.history.is_empty() {
let chat: String = app.history[app.history_thread_index]
.iter()
.map(|m| m.to_string())
.collect();
match std::fs::write(app.config.archive_file_name.clone(), chat) {
if !app.history.chat.is_empty() {
match std::fs::write(
&app.config.archive_file_name,
app.history.chat[app.history.index].join(""),
) {
Ok(_) => {
let notif = Notification::new(
format!(
Expand All @@ -150,8 +164,10 @@ pub fn handle_key_events(
}
}
FocusedBlock::Chat | FocusedBlock::Prompt => {
let chat: String = app.chat.iter().map(|m| m.to_string()).collect();
match std::fs::write(app.config.archive_file_name.clone(), chat) {
match std::fs::write(
app.config.archive_file_name.clone(),
app.chat.messages.join(""),
) {
Ok(_) => {
let notif = Notification::new(
format!(
Expand All @@ -173,29 +189,32 @@ pub fn handle_key_events(
}
}
}
_ => (),
},

// Switch the focus
KeyCode::Tab => {
if app.show_history_popup {
match app.focused_block {
FocusedBlock::Preview => app.focused_block = FocusedBlock::History,
FocusedBlock::History => app.focused_block = FocusedBlock::Preview,
_ => (),
match app.focused_block {
FocusedBlock::Chat => {
app.scroll = 0;
app.focused_block = FocusedBlock::Prompt;
}
} else {
match app.focused_block {
FocusedBlock::Chat => {
app.scroll = 0;
app.focused_block = FocusedBlock::Prompt;
}
FocusedBlock::Prompt => {
app.scroll = app.chat_scroll;
app.focused_block = FocusedBlock::Chat;
}
_ => (),
FocusedBlock::Prompt => {
app.scroll = 0;
app.focused_block = FocusedBlock::Chat;
}

//TODO: focus on history popup
_ => (),
}
// if app.show_history_popup {
// match app.focused_block {
// FocusedBlock::Preview => app.focused_block = FocusedBlock::History,
// FocusedBlock::History => app.focused_block = FocusedBlock::Preview,
// _ => (),
// }
// } else {
// }
}

// kill the app
Expand All @@ -207,38 +226,32 @@ pub fn handle_key_events(

// Show help
KeyCode::Char(c) if c == app.config.key_bindings.show_help => {
app.show_help_popup = true;
app.focused_block = FocusedBlock::Help;
}

// Show history
KeyCode::Char(c) if c == app.config.key_bindings.show_history => {
app.show_history_popup = true;
app.focused_block = FocusedBlock::History;
}

// Discard help & history popups
KeyCode::Esc => {
app.show_help_popup = false;
if app.show_history_popup {
app.show_history_popup = false;
app.focused_block = FocusedBlock::Prompt;
app.scroll = 0;
}
app.focused_block = FocusedBlock::Prompt;
}

_ => {}
},

Mode::Insert => match key_event.code {
KeyCode::Enter => app.prompt.push('\n'),
KeyCode::Enter => app.prompt.message.push('\n'),

KeyCode::Char(c) => {
app.prompt.push(c);
app.prompt.message.push(c);
}

KeyCode::Backspace => {
if app.prompt.len() > 3 {
app.prompt.pop();
if app.prompt.message.len() > 3 {
app.prompt.message.pop();
}
}

Expand Down
Loading

0 comments on commit ec234aa

Please sign in to comment.